19 Commits
Author SHA1 Message Date
BlackAngelTV 5cc8785eba Merge pull request 'feat(notifications): notify when long commands finish, with duration and exit status' (#37) from feat/cmd-finish-notifications into main
Reviewed-on: #37
2026-11-12 07:24:19 +01:00
BlackAngelTV 02f43b2ee9 Merge pull request 'feat(tab-bar): add command status and cwd indicators, close and new tab buttons' (#34) from feat/tab-bar-indicators into main
Reviewed-on: #34
2026-11-11 20:19:40 +01:00
BlackAngelTV 97a686f33d Merge remote-tracking branch 'origin/main' into feat/tab-bar-indicators
# Conflicts:
#	kittens/file_manager/main.go
2026-11-11 20:18:12 +01:00
BlackAngelTV 787eb26f32 Merge pull request 'docs(kittens): document the file manager panel' (#38) from docs/file-manager-reference into main
Reviewed-on: #38
2026-11-11 20:12:43 +01:00
BlackAngelTV 59f42aec03 Merge remote-tracking branch 'origin/main' into docs/file-manager-reference
# Conflicts:
#	docs/changelog.rst
#	docs/kittens/file-manager.rst
2026-11-11 20:09:08 +01:00
BlackAngelTV c45bed6a94 Merge pull request 'feat(file-manager): fuzzy search, action palette and quick open' (#39) from feat/file-manager-search into main
Reviewed-on: #39
2026-11-11 20:06:23 +01:00
BlackAngelTV 683d65455e build(docs): use the checkout tool environment when it exists
The documentation needs extensions that are not installed system-wide, so
make html failed on a fresh shell even though the project already keeps them in
the root tool environment. Falling back to sphinx-build keeps the target
working when no environment is present.
2026-11-11 19:38:09 +01:00
BlackAngelTV e215c2b8d6 docs(changelog): note the file manager search and palette 2026-11-11 19:07:03 +01:00
BlackAngelTV d2562b9418 docs(file-manager): document search, the action palette and quick open 2026-11-11 19:07:03 +01:00
BlackAngelTV 8b13806ac5 feat(file-manager): filter the listing and open files faster
The panel could only be browsed entry by entry, which is slower than cd and ls
in a large directory. Typing / now filters the listing with the same fuzzy
matcher as the command palette, typing : lists every action with its
description from a single catalog, and o/t open the selection in a new tab or
OS window. Sizes are read once when the directory is listed so that sort_by
size does not need to stat the entries again.
2026-11-11 19:07:03 +01:00
BlackAngelTV 8d481f8d1e docs(changelog): note the file manager documentation update 2026-11-11 18:59:26 +01:00
BlackAngelTV b8eb3b20c8 docs(kittens): list the file manager in the kittens overview 2026-11-11 18:59:26 +01:00
BlackAngelTV 641fe9b910 docs(kittens): document file manager shell integration and limits 2026-11-11 18:59:26 +01:00
BlackAngelTV de13151af1 fix(file-manager): open the selection with Enter instead of changing directory
Enter quit the panel and cd'ed the shell, which silently did nothing when the
panel ran in a dock, where there is no shell to move. Enter now behaves like
the right arrow and descends into a directory in place, while Ctrl+Enter keeps
the shell directory change and no longer depends on the selection.
2026-11-09 12:24:06 +01:00
BlackAngelTV fab02aa915 feat(tab-bar): add clickable close buttons to tabs
Tabs could only be closed with the keyboard or the middle mouse button, which
is not discoverable. Draw a small cross at the start of each horizontal tab,
close the tab when it is clicked, and avoid starting a drag from the button.
2026-11-09 11:14:07 +01:00
BlackAngelTV f324f5fff2 feat(tab-bar): show the new tab button by default
The + button was only visible when explicitly enabled or while dragging a
window, so new tabs could not be created from the tab bar out of the box. Show
it at rest and keep the tab bar visible with a single tab.
2026-11-09 11:14:07 +01:00
BlackAngelTV bcf3fdff7b feat(tab-bar): add command status and abbreviated cwd indicators
The tab bar only showed the window title, so it was impossible to tell at a
glance whether the last command failed or which directory a tab was in. Expose
the active window's last exit status and a compact working directory to
tab_title_template, and refresh the tab bar when a command finishes.
2026-11-09 11:14:07 +01:00
BlackAngelTV 90e6355841 Merge pull request 'Feat/file manager panel' (#32) from feat/file-manager-panel into main
Reviewed-on: #32
2026-11-09 08:52:36 +01:00
BlackAngelTV ea29472b27 Merge pull request 'feat(config): add named configuration profiles' (#33) from feat/config-profiles into main
Reviewed-on: #33
2026-11-09 08:52:24 +01:00
82 changed files with 165 additions and 5118 deletions

No files matched your search

-68
View File
@@ -1,68 +0,0 @@
# Continuous integration: every pull request and every push to main must pass
# the linter, the build and the tests. Packaging lives in package.yml, which
# only runs when the version file changes.
name: CI
on:
pull_request:
push:
branches: [main]
# A version-only commit is released by package.yml, which runs the same
# checks on the package build; CI would build that commit a second time.
paths-ignore: [version]
workflow_dispatch:
# A new push on the same branch supersedes the previous run, but main builds run
# to completion so a broken merge is always reported.
concurrency:
group: ci-${{ github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
check:
# Arch Linux host runner: kitty builds against the Arch toolchain (base-devel,
# go, python, harfbuzz, shader-slang...) and makepkg refuses to run as root.
runs-on: arch-host
defaults:
run:
shell: bash
steps:
- uses: actions/checkout@v4
- name: Install the build dependencies
run: ./packaging/install-ci-deps.sh
- name: Check the version files agree
run: ./packaging/check-version.sh
- name: Lint Python
run: |
ruff check .
ruff format --check .
- name: Check Go formatting
run: |
# Generated files only exist after ./dev.sh build and are not tracked,
# so only the committed sources are checked.
unformatted="$(git ls-files -z '*.go' | xargs -0 gofmt -s -l)"
if [ -n "$unformatted" ]; then
echo "::error::gofmt is required for:"
echo "$unformatted"
exit 1
fi
- name: Build
run: ./dev.sh build
# The Go packages import generated code and embedded data produced by the
# build above, so vet and tests cannot run on a bare checkout.
- name: Vet
run: go vet ./kittens/file_manager/
- name: Test
run: go test --tags testing ./kittens/file_manager/
- name: Smoke test the binaries
run: |
./kitty/launcher/kitty --version
./kitty/launcher/kitten --version
-252
View File
@@ -1,252 +0,0 @@
# Release pipeline. A change to the version file on main is the only thing that
# publishes: the package is built once from that exact commit, the checks run on
# that same build, and it is attached to a Gitea release and pushed to the
# pacman repository at repo.laxacube.ch.
#
# Required secrets: RELEASE_TOKEN (release API), REPO_TOKEN (pacman repository).
name: Release
on:
push:
branches: [main]
# Only a version bump releases; every other commit stays on the CI path.
paths: [version]
workflow_dispatch:
permissions:
contents: write
# Releases are ordered: a second run waits instead of racing for the same tag.
concurrency:
group: release
cancel-in-progress: false
jobs:
# A single job so the package is compiled only once: makepkg builds kitty and
# the Go tools, the checks below run on that build tree, and publishing comes
# last, so a release never pays for a second build of the same commit.
release:
runs-on: arch-host
defaults:
run:
shell: bash
steps:
- uses: actions/checkout@v4
- name: Install the build dependencies
run: ./packaging/install-ci-deps.sh
- name: Check the version files agree
run: ./packaging/check-version.sh
- name: Lint Python
run: |
ruff check .
ruff format --check .
- name: Check Go formatting
run: |
unformatted="$(git ls-files -z '*.go' | xargs -0 gofmt -s -l)"
if [ -n "$unformatted" ]; then
echo "::error::gofmt is required for:"
echo "$unformatted"
exit 1
fi
- name: Read the version file
id: version
run: echo "version=$(./packaging/check-version.sh)" >> "$GITHUB_OUTPUT"
- name: Build the Arch package
id: package
run: |
set -euo pipefail
# makepkg creates src/ and pkg/ next to the PKGBUILD, so build in a
# scratch directory to leave the checkout untouched.
work="$RUNNER_TEMP/fws-kitty-${{ steps.version.outputs.version }}"
rm -rf "$work"
mkdir -p "$work"
cp packaging/PKGBUILD "$work/"
cd "$work"
# Pin the build to the commit being released: main may already have
# moved on by the time makepkg clones the repository. The source tree
# is kept (no --cleanbuild) so the checks below run in it instead of
# rebuilding the project a second time.
FWS_SOURCE_REF="commit=$GITHUB_SHA" \
makepkg --noconfirm --nodeps --force
echo "FWS_SRC=$work/src/fws-kitty" >> "$GITHUB_ENV"
# kitty's linux-package target installs straight into the staging root,
# so the built binaries live there rather than in the source tree.
echo "FWS_PKG=$work/pkg/fws-kitty" >> "$GITHUB_ENV"
# ls prints ./*, which must not leak into the asset name or the
# X-Filename header of the pacman upload.
asset="$(ls -1 ./*.pkg.tar.zst | grep -v -- '-debug-' | head -n 1)"
asset="${asset#./}"
sha256sum "$asset" > "$asset.sha256"
cat "$asset.sha256"
echo "file=$work/$asset" >> "$GITHUB_OUTPUT"
echo "name=$asset" >> "$GITHUB_OUTPUT"
# These import generated code and embedded data that only exist after a
# build, so they run in the makepkg tree above, not on the bare checkout.
- name: Vet the Go code
run: |
set -euo pipefail
cd "$FWS_SRC"
go vet ./kittens/file_manager/
- name: Test the Go code
run: |
set -euo pipefail
cd "$FWS_SRC"
go test --tags testing ./kittens/file_manager/
- name: Smoke test the binaries
env:
VERSION: ${{ steps.version.outputs.version }}
run: |
set -euo pipefail
"$FWS_PKG/usr/bin/kitty" --version
"$FWS_PKG/usr/bin/kitten" --version
# The release announces the fork version, not the kitty one.
"$FWS_PKG/usr/bin/kitty" --version | grep -qF "fws-kitty $VERSION"
- name: Publish the Gitea release
env:
RELEASE_TOKEN: ${{ secrets.RELEASE_TOKEN }}
VERSION: ${{ steps.version.outputs.version }}
PACKAGE_NAME: ${{ steps.package.outputs.name }}
PACKAGE_FILE: ${{ steps.package.outputs.file }}
run: |
set -euo pipefail
# Without the token every API call answers 401 and the failure would
# look like a missing release instead of a missing secret.
if [ -z "${RELEASE_TOKEN:-}" ]; then
echo "::error::RELEASE_TOKEN is not set: cannot create the release."
exit 1
fi
api="$GITHUB_SERVER_URL/api/v1/repos/$GITHUB_REPOSITORY"
tag="v$VERSION"
auth="Authorization: token $RELEASE_TOKEN"
# A pacman version is immutable: the repository index, the CDN in
# front of it and every client cache the package by its name, so a
# second build published under the same name leaves them disagreeing
# and pacman reports the download as corrupted. Once repo.laxacube.ch
# serves the name there is nothing left to publish: a re-run is a
# no-op, and a changed build needs a pkgrel bump so it gets its own
# package name.
local_sha256="$(cut -d' ' -f1 "$PACKAGE_FILE.sha256")"
repo_sha256=""
if curl -fsSL "https://repo.laxacube.ch/x86_64/$PACKAGE_NAME" -o "$RUNNER_TEMP/repo.pkg" 2>/dev/null; then
repo_sha256="$(sha256sum "$RUNNER_TEMP/repo.pkg" | cut -d' ' -f1)"
fi
if [ -n "$repo_sha256" ]; then
if [ "$repo_sha256" = "$local_sha256" ]; then
echo "$PACKAGE_NAME is already published to repo.laxacube.ch, nothing to do"
else
echo "::warning::$PACKAGE_NAME is already published to repo.laxacube.ch with sha256 $repo_sha256, this build is $local_sha256 and is not published"
echo "::warning::bump pkgrel in packaging/PKGBUILD to publish this build under its own package name"
fi
echo "SKIP_PUBLISH=1" >> "$GITHUB_ENV"
exit 0
fi
release_id="$(curl -sS -H "$auth" "$api/releases/tags/$tag" | python3 -c '
import json, sys
try:
print(json.load(sys.stdin).get("id") or "")
except Exception:
print("")
')"
if [ -z "$release_id" ]; then
body="$(printf 'FWS-Kitty %s\n\nPaquet Arch du fork FWS-Kitty.\n\nInstallation :\n\n sudo pacman -U %s\n\nVérification du téléchargement :\n\n sha256sum -c %s.sha256\n' "$VERSION" "$PACKAGE_NAME" "$PACKAGE_NAME")"
payload="$(BODY="$body" TAG="$tag" VERSION="$VERSION" python3 -c '
import json, os
print(json.dumps({
"tag_name": os.environ["TAG"],
"name": "FWS-Kitty " + os.environ["VERSION"],
"body": os.environ["BODY"],
"draft": False,
"prerelease": False,
}))
')"
release_id="$(curl -sS --fail-with-body -X POST -H "$auth" \
-H 'Content-Type: application/json' -d "$payload" "$api/releases" \
| python3 -c 'import json, sys; print(json.load(sys.stdin)["id"])')"
fi
echo "release_id=$release_id"
# A re-run must replace its own artefacts instead of failing on them.
assets="$(curl -sS -H "$auth" "$api/releases/$release_id/assets")"
attach() {
file="$1"
name="$2"
asset_id="$(ASSETS="$assets" NAME="$name" python3 -c '
import json, os
try:
assets = json.loads(os.environ["ASSETS"])
except Exception:
assets = []
print(next((a["id"] for a in assets if a.get("name") == os.environ["NAME"]), ""))
')"
if [ -n "$asset_id" ]; then
curl -sS -X DELETE -H "$auth" "$api/releases/assets/$asset_id" -o /dev/null
fi
curl -sS --fail-with-body -X POST -H "$auth" \
-F "attachment=@$file" "$api/releases/$release_id/assets?name=$name" -o /dev/null
echo "attached $name"
}
attach "$PACKAGE_FILE" "$PACKAGE_NAME"
attach "$PACKAGE_FILE.sha256" "$PACKAGE_NAME.sha256"
- name: Push the package to repo.laxacube.ch
# Skipped when the release step found the version already published, so
# a re-run can never replace the bytes pacman clients are served.
if: env.SKIP_PUBLISH != '1'
env:
REPO_TOKEN: ${{ secrets.REPO_TOKEN }}
PACKAGE_NAME: ${{ steps.package.outputs.name }}
PACKAGE_FILE: ${{ steps.package.outputs.file }}
run: |
set -euo pipefail
if [ -z "${REPO_TOKEN:-}" ]; then
echo "::warning::REPO_TOKEN is not set: the release exists but repo.laxacube.ch was not updated."
exit 0
fi
curl -sS --fail-with-body -X POST https://repo.laxacube.ch/api/packages \
-H "Authorization: Bearer $REPO_TOKEN" \
-H "X-Filename: $PACKAGE_NAME" \
-H 'Content-Type: application/octet-stream' \
--data-binary "@$PACKAGE_FILE"
echo
# The index is rebuilt server-side and the file is served through a
# CDN, so a HEAD is not enough: the index and the file can disagree
# for as long as the CDN caches the previous build under this name,
# and the checksum is exactly what pacman verifies before installing.
# A freshly accepted upload is not routable instantly, so an absent
# file is retried before giving up; different bytes are a real
# mismatch and fail at once, since that is what breaks pacman.
url="https://repo.laxacube.ch/x86_64/$PACKAGE_NAME"
expected="$(cut -d' ' -f1 "$PACKAGE_FILE.sha256")"
code=000
for _ in $(seq 1 24); do
code="$(curl -sS -o "$RUNNER_TEMP/served.pkg" -w '%{http_code}' "$url" || true)"
if [ "$code" = 200 ]; then
served="$(sha256sum "$RUNNER_TEMP/served.pkg" | cut -d' ' -f1)"
if [ "$served" = "$expected" ]; then
echo "published $url"
exit 0
fi
echo "::error::$url serves sha256 $served instead of $expected"
echo "::error::the CDN is still caching another build under this name: purge it before re-running"
exit 1
fi
sleep 5
done
if [ "$code" = 404 ]; then
echo "::warning::$url is not visible yet; the repository accepted the upload, pacman will see it once the index is rebuilt"
exit 0
fi
echo "::error::$url answered HTTP $code after the upload"
exit 1
-4
View File
@@ -13,10 +13,6 @@
/.venv /.venv
/tags /tags
/build/ /build/
# makepkg output: built locally and published by the release workflow, never
# committed (the artefacts are large binaries that are reproducible from a tag).
/packaging/*.pkg.tar.zst*
/packaging/*.tar.gz
/fonts/ /fonts/
/shaders/ /shaders/
/linux-package/ /linux-package/
-394
View File
@@ -1,394 +0,0 @@
# Raccourcis clavier de FWS-Kitty
Tous les raccourcis de ce document sont **actifs par défaut** : kitty et les
fonctions ajoutées par FWS s'utilisent au lancement sans écrire une seule ligne
de configuration. Le fichier couvre les raccourcis globaux du terminal, ceux des
fonctions FWS (gestionnaire de fichiers, historique du presse-papiers,
restauration de session) et les touches des interfaces intégrées (kittens).
Les tableaux reflètent les valeurs de `kitty/options/definition.py`. La palette
de commandes (`Ctrl+Shift+F3`) liste en direct toutes les actions, leur touche
et leur catégorie, y compris les actions sans raccourci.
> **Aide rapide** : `Ctrl+Shift+Alt+H` (`kitty_mod+alt+h`) ouvre le panneau latéral qui
> liste tous les raccourcis, avec recherche et catégories. Dans le shell kitty,
> `help` fait la même chose.
## Conventions
| Notation | Signification |
| --- | --- |
| `kitty_mod` | Alias de `Ctrl+Shift` sous Linux, BSD et macOS, redéfinissable avec l'option `kitty_mod`. |
| `Ctrl+Shift+X` | Maintenir `Ctrl` et `Shift`, puis appuyer sur `X`. |
| `Ctrl+Shift+P` puis `F` | Séquence : relâcher la première combinaison avant de presser `F`. |
| `→`, `←`, `↑`, `↓` | Flèches de direction. |
| `Entrée`, `Échap`, `Retour arrière`, `Suppr` | Touches `Enter`, `Escape`, `Backspace`, `Delete`. |
| `Page↑`, `Page↓`, `Début`, `Fin` | Touches `Page Up`, `Page Down`, `Home`, `End`. |
| `KP+`, `KP-` | Touches `+` et `-` du pavé numérique. |
`kitty_mod` vaut `Ctrl+Shift` sur toutes les plateformes : `kitty_mod+c` se lit
`Ctrl+Shift+C`, même sous macOS. Les raccourcis macOS habituels (`Cmd+C`,
`Cmd+V`, `Cmd+T`…) sont des mappings distincts, regroupés plus bas.
## Fonctions ajoutées par FWS
| Touche | Action |
| --- | --- |
| `Ctrl+Shift+E` | Ouvre le gestionnaire de fichiers dans un dock à gauche de la fenêtre. La touche est la même sous macOS. |
| `Ctrl+Shift+Alt+V` (`kitty_mod+alt+v`) | Colle une entrée de l'historique du presse-papiers. |
| `Ctrl+Shift+Alt+F` (`kitty_mod+alt+f`) | Demande une recherche floue, puis colle l'entrée choisie. |
| `Ctrl+Shift+Alt+R` (`kitty_mod+alt+r`) | Restaure la session enregistrée à la dernière fermeture de kitty. |
| `Ctrl+Shift+Alt+H` (`kitty_mod+alt+h`) | Ouvre le panneau latéral de tous les raccourcis. |
Deux fonctions FWS ne demandent aucune touche :
- Les **notifications de fin de commande** sont actives avec
`notify_on_cmd_finish unfocused` : une commande de plus de 5 secondes notifie
quand la fenêtre n'est plus au premier plan, avec sa durée et son code de
sortie.
- La **barre d'onglets** affiche le code de sortie des commandes en échec
(`✘ code`), le répertoire courant abrégé et les boutons `×` (fermer l'onglet)
et `+` (nouvel onglet). Elle est visible dès le premier onglet.
> `Ctrl+Shift+E` ouvrait auparavant les URLs visibles (`open_url`). Le
> gestionnaire de fichiers prend la touche par défaut. Pour retrouver l'ancien
> comportement, ajoutez `map ctrl+shift+e open_url_with_hints` dans
> `kitty.conf` ; le panneau reste accessible avec `kitten file-manager`.
## Presse-papiers
| Touche | Action |
| --- | --- |
| `Ctrl+Shift+C` | Copie la sélection dans le presse-papiers. |
| `Ctrl+Shift+V` | Colle le presse-papiers. |
| `Ctrl+Shift+S` | Colle la sélection primaire. |
| `Maj+Inser` | Colle la sélection primaire. |
| `Ctrl+Shift+Alt+V` | Colle une entrée de l'historique. |
| `Ctrl+Shift+Alt+F` | Recherche dans l'historique puis colle. |
| `Ctrl+Shift+O` | Passe la sélection à un programme (navigateur par défaut sans argument). |
## Défilement et historique
| Touche | Action |
| --- | --- |
| `Ctrl+Shift+↑` ou `Ctrl+Shift+K` | Défile d'une ligne vers le haut. |
| `Ctrl+Shift+↓` ou `Ctrl+Shift+J` | Défile d'une ligne vers le bas. |
| `Ctrl+Shift+Page↑` | Défile d'une page vers le haut. |
| `Ctrl+Shift+Page↓` | Défile d'une page vers le bas. |
| `Ctrl+Shift+Début` | Va au début de l'historique. |
| `Ctrl+Shift+Fin` | Va à la fin de l'historique. |
| `Ctrl+Shift+Z` | Va au prompt précédent. |
| `Ctrl+Shift+X` | Va au prompt suivant. |
| `Ctrl+Shift+H` | Affiche tout l'historique dans un pager. |
| `Ctrl+Shift+G` | Affiche la sortie de la dernière commande dans un pager. |
| `Ctrl+Shift+/` | Recherche dans l'historique dans un pager. |
| `Ctrl+Shift+Alt+S` | Recherche avec surlignage sur place (`n`/`N` pour naviguer, `Échap` pour quitter). |
## Fenêtres
| Touche | Action |
| --- | --- |
| `Ctrl+Shift+Entrée` | Nouvelle fenêtre dans l'onglet courant. |
| `Ctrl+Shift+N` | Nouvelle fenêtre du système (OS Window). |
| `Ctrl+Shift+W` | Ferme la fenêtre courante. |
| `Ctrl+Shift+]` | Fenêtre suivante. |
| `Ctrl+Shift+[` | Fenêtre précédente. |
| `Ctrl+Shift+F` | Avance la fenêtre dans la disposition. |
| `Ctrl+Shift+B` | Recule la fenêtre dans la disposition. |
| ``Ctrl+Shift+` `` | Place la fenêtre au premier plan de la disposition. |
| `Ctrl+Shift+R` | Démarre le redimensionnement au clavier. |
| `Ctrl+Shift+1` … `Ctrl+Shift+0` | Active la 1re … 10e fenêtre. |
| `Ctrl+Shift+F7` | Active la fenêtre visible sous le pointeur. |
| `Ctrl+Shift+F8` | Échange la fenêtre courante avec celle sous le pointeur. |
## Onglets
| Touche | Action |
| --- | --- |
| `Ctrl+Shift+→` | Onglet suivant. |
| `Ctrl+Shift+←` | Onglet précédent. |
| `Ctrl+Tab` / `Ctrl+Shift+Tab` | Onglet suivant / précédent. |
| `Ctrl+Shift+T` | Nouvel onglet. |
| `Ctrl+Shift+Q` | Ferme l'onglet courant. |
| `Ctrl+Shift+.` | Déplace l'onglet vers la droite. |
| `Ctrl+Shift+,` | Déplace l'onglet vers la gauche. |
| `Ctrl+Shift+Alt+T` | Renomme l'onglet courant. |
| `Ctrl+Shift+F11` | Bascule le plein écran. |
| `Ctrl+Shift+F10` | Bascule la maximisation. |
## Dispositions
| Touche | Action |
| --- | --- |
| `Ctrl+Shift+L` | Passe à la disposition suivante. |
## Taille de police
| Touche | Action |
| --- | --- |
| `Ctrl+Shift+=`, `Ctrl+Shift++` ou `Ctrl+Shift+KP+` | Agrandit la police de 2 points. |
| `Ctrl+Shift+-` ou `Ctrl+Shift+KP-` | Réduit la police de 2 points. |
| `Ctrl+Shift+Retour arrière` | Rétablit la taille configurée. |
## Sélectionner du texte (hints)
| Touche | Action |
| --- | --- |
| `Ctrl+Shift+P` puis `F` | Insère le chemin sélectionné dans la ligne de commande. |
| `Ctrl+Shift+P` puis `Maj+F` | Ouvre le chemin sélectionné. |
| `Ctrl+Shift+P` puis `C` | Choisit un fichier et l'insère. |
| `Ctrl+Shift+P` puis `D` | Choisit un répertoire et l'insère. |
| `Ctrl+Shift+P` puis `L` | Insère la ligne sélectionnée. |
| `Ctrl+Shift+P` puis `W` | Insère le mot sélectionné. |
| `Ctrl+Shift+P` puis `H` | Insère le hash (commit git) sélectionné. |
| `Ctrl+Shift+P` puis `N` | Ouvre le fichier à la ligne indiquée (`fichier:42`). |
| `Ctrl+Shift+P` puis `Y` | Ouvre le lien hypertexte sélectionné. |
Dans une sélection par hints, tapez l'étiquette affichée sur le texte visé ;
`Entrée` ou `Espace` valide une étiquette vide lorsque les hints utilisent
plusieurs lettres.
## Sessions
| Touche | Action |
| --- | --- |
| `Ctrl+Shift+Alt+R` | Restaure les onglets, dispositions, répertoires et titres de la dernière session. |
La même restauration est disponible au démarrage :
```sh
kitty --session=last
```
`save_as_session`, `goto_session` et `close_session` n'ont pas de touche par
défaut : lancez-les depuis la palette de commandes (`Ctrl+Shift+F3`) ou
associez-les dans `kitty.conf`.
## Divers
| Touche | Action |
| --- | --- |
| `Ctrl+Shift+F1` | Ouvre la documentation de kitty. |
| `Ctrl+Shift+F3` | Ouvre la palette de commandes. |
| `Ctrl+Shift+E` | Ouvre le gestionnaire de fichiers (FWS). |
| `Ctrl+Shift+F2` | Ouvre `kitty.conf` dans l'éditeur. |
| `Ctrl+Shift+F5` | Recharge la configuration. |
| `Ctrl+Shift+F6` | Affiche la configuration effective. |
| `Ctrl+Shift+U` | Saisie de caractères Unicode. |
| `Ctrl+Shift+Échap` | Ouvre un shell kitty (contrôle à distance). |
| `Ctrl+Shift+A` puis `M` | Augmente l'opacité du fond. |
| `Ctrl+Shift+A` puis `L` | Diminue l'opacité du fond. |
| `Ctrl+Shift+A` puis `1` | Fond totalement opaque. |
| `Ctrl+Shift+A` puis `D` | Rétablit l'opacité configurée. |
| `Ctrl+Shift+Suppr` | Réinitialise le terminal. |
| `Ctrl+Shift+Alt+H` | Envoie `Hello World` au terminal (exemple fourni par kitty). |
## Raccourcis macOS
Sous macOS, les raccourcis par défaut de kitty sont majoritairement en `Cmd`,
tandis que les raccourcis FWS basés sur `kitty_mod` restent en `Ctrl+Shift`.
Les entrées suivantes complètent les tableaux précédents.
| Touche | Action |
| --- | --- |
| `Cmd+C` | Copie, ou transmet `Ctrl+C` au programme s'il n'y a pas de sélection. |
| `Cmd+V` | Colle le presse-papiers. |
| `Cmd+↑` / `Cmd+↓` | Défile d'une ligne vers le haut / le bas. |
| `Cmd+Page↑` / `Cmd+Page↓` | Défile d'une page vers le haut / le bas. |
| `Cmd+Début` / `Cmd+Fin` | Début / fin de l'historique. |
| `Cmd+F` | Recherche dans l'historique. |
| `Cmd+Entrée` | Nouvelle fenêtre. |
| `Cmd+N` | Nouvelle fenêtre du système. |
| `Cmd+W` | Ferme l'onglet ; `Cmd+Shift+W` ferme la fenêtre du système. |
| `Cmd+T` | Nouvel onglet. |
| `Cmd+Shift+]` / `Cmd+Shift+[` | Onglet suivant / précédent. |
| `Cmd+Shift+I` | Renomme l'onglet. |
| `Cmd+1` … `Cmd+9` | Active la 1re … 9e fenêtre. |
| `Cmd+R` | Redimensionnement au clavier. |
| ``Cmd+` `` / ``Cmd+Shift+` `` | Fenêtre du système suivante / précédente. |
| `Cmd++`, `Cmd+=`, `Cmd+Shift+=` | Agrandit la police. |
| `Cmd+-`, `Cmd+Shift+-` | Réduit la police. |
| `Cmd+0` | Rétablit la taille de police. |
| `Cmd+,` | Ouvre `kitty.conf`. |
| `Ctrl+Cmd+,` | Recharge la configuration. |
| `Alt+Cmd+,` | Affiche la configuration effective. |
| `Alt+Cmd+R` | Réinitialise le terminal. |
| `Ctrl+Cmd+F` | Bascule le plein écran. |
| `Ctrl+Cmd+Espace` | Saisie Unicode. |
| `Cmd+K` | Efface l'écran jusqu'au curseur. |
| `Alt+Cmd+K` | Efface l'historique. |
| `Cmd+L` | Efface la dernière commande. |
| `Ctrl+Cmd+L` | Efface l'écran et l'historique. |
| `Alt+Cmd+S` | Active la saisie clavier sécurisée. |
| `Cmd+Shift+/` | Ouvre le site de kitty. |
| `Cmd+H` / `Alt+Cmd+H` | Masque kitty / les autres applications. |
| `Cmd+M` | Réduit la fenêtre. |
| `Cmd+Q` | Quitte kitty. |
## Barre d'onglets et souris
| Geste | Action |
| --- | --- |
| Clic gauche sur un onglet | Active l'onglet. |
| Clic sur `×` | Ferme l'onglet. |
| Clic sur `+` | Ouvre un nouvel onglet. |
| Clic du milieu sur un onglet | Ferme l'onglet. |
| Glisser un onglet | Réordonne, détache ou déplace l'onglet. |
| Clic gauche dans le gestionnaire de fichiers | Sélectionne l'entrée. |
## Gestionnaire de fichiers (`Ctrl+Shift+E`)
| Touche | Action |
| --- | --- |
| `Entrée` | Entre dans le répertoire sélectionné, ou ouvre le fichier dans l'éditeur dans un nouvel onglet. |
| `→` ou `L` | Entre dans le répertoire sélectionné sans toucher au shell. |
| `←`, `Retour arrière` ou `H` | Remonte au répertoire parent. |
| `Ctrl+Entrée` ou `C` | Déplace le shell vers le répertoire affiché puis ferme le panneau. |
| `↑` ou `K` | Sélection précédente. |
| `↓` ou `J` | Sélection suivante. |
| `Tab` / `Maj+Tab` | Sélection suivante / précédente. |
| `Page↑` ou `Ctrl+B` | Sélection précédente d'une page. |
| `Page↓` ou `Ctrl+F` | Sélection suivante d'une page. |
| `Début` ou `G` | Première entrée. |
| `Fin` ou `Maj+G` | Dernière entrée. |
| `/` | Filtre la liste par recherche floue ; `Entrée` ouvre la sélection, `Échap` efface la requête. |
| `:` | Ouvre la palette des actions du panneau ; `Entrée` exécute l'action. |
| `O` | Ouvre le fichier sélectionné dans un nouvel onglet. |
| `T` | Ouvre le fichier sélectionné dans une nouvelle fenêtre du système. |
| `N` | Crée un fichier. |
| `Maj+N` ou `A` | Crée un répertoire. |
| `R` | Renomme l'entrée sélectionnée. |
| `D` | Supprime l'entrée après confirmation par `Y` (jamais récursivement). |
| `Y` | Copie le chemin dans le presse-papiers. |
| `.` | Affiche ou masque les entrées cachées. |
| `Ctrl+R` | Recharge le répertoire. |
| `Échap` ou `Q` | Ferme le panneau sans changer de répertoire. |
Toutes ces touches se redéfinissent dans `~/.config/kitty/file-manager.conf`
avec la syntaxe `map <touche> <action>`.
## Palette de commandes (`Ctrl+Shift+F3`)
| Touche | Action |
| --- | --- |
| Texte | Filtre les résultats. |
| `Entrée` | Exécute l'action sélectionnée. |
| `Échap` | Efface la requête, ou ferme la palette si elle est vide. |
| `↑`, `Maj+Tab`, `Ctrl+K` ou `Ctrl+P` | Sélection précédente. |
| `↓`, `Tab`, `Ctrl+J` ou `Ctrl+N` | Sélection suivante. |
| `Page↑` / `Page↓` | Sélection précédente / suivante d'une page. |
| `Début` / `Fin` | Premier / dernier résultat. |
| `Retour arrière` | Efface le dernier caractère de la requête. |
| `F12` | Affiche ou masque les actions sans raccourci. |
## Panneau d'aide (`help`)
Dans le shell kitty (`Ctrl+Shift+Échap`), `help` sans argument ouvre un panneau
latéral qui liste tous les raccourcis actifs, classés par catégorie, avec une
recherche rapide. Depuis un terminal : `kitty +kitten help` ; le raccourci
par défaut `Ctrl+Shift+Alt+H` (`kitty_mod+alt+h`) ouvre le même panneau.
| Touche | Action |
| --- | --- |
| Texte | Filtre les raccourcis. |
| `Échap` | Efface la requête, puis ferme le panneau. |
| `↑` / `↓`, `Ctrl+K` / `Ctrl+J` | Raccourci précédent / suivant. |
| `Tab` / `Maj+Tab` | Raccourci suivant / précédent. |
| `Page↑` / `Page↓` | Défile d'une page. |
| `Début` / `Fin` | Premier / dernier raccourci. |
| `F12` | Affiche ou masque les actions sans raccourci. |
| `Entrée` | Sans effet : le panneau est en lecture seule. |
## Historique du presse-papiers (`Ctrl+Shift+Alt+V`)
| Touche | Action |
| --- | --- |
| Numéro affiché devant une entrée | Colle immédiatement cette entrée. |
| `Échap` | Ferme la liste sans rien coller. |
`Ctrl+Shift+Alt+F` commence par demander une requête floue, puis affiche la
même liste. L'historique vit en mémoire uniquement : il disparaît à la
fermeture de kitty et les copies marquées privées n'y sont jamais enregistrées.
## Saisie Unicode (`Ctrl+Shift+U`)
| Touche | Action |
| --- | --- |
| `F1` … `F4` ou `Ctrl+1` … `Ctrl+4` | Change de mode. |
| `Ctrl+[` / `Ctrl+]` ou `Ctrl+Tab` / `Ctrl+Shift+Tab` | Change de mode. |
| `Entrée` | Insère le caractère dont le code hexadécimal est saisi. |
| `↑` / `↓` | Caractère récent précédent / suivant. |
| `.` puis index à deux chiffres | Choisit un caractère récent. |
| Flèches ou `Tab` | Sélectionne un caractère parmi les correspondances du mode Nom. |
| `Espace` puis `.` et l'index | Sélectionne une correspondance sans les flèches. |
## Hints
| Touche | Action |
| --- | --- |
| Étiquette affichée | Sélectionne le texte marqué. |
| `Entrée` ou `Espace` | Valide une étiquette vide quand plusieurs lettres sont nécessaires. |
| Clic sur le texte marqué | Sélectionne sans taper l'étiquette. |
## Diff (`kitten diff`)
| Touche | Action |
| --- | --- |
| `Q` | Quitte. |
| `K` / `↑`, `J` / `↓` | Défile d'une ligne. |
| `Page↑` / `Page↓` | Défile d'une page. |
| `Début` / `Fin` | Haut / bas du fichier. |
| `Espace` ou `Ctrl+F`, `Ctrl+B` | Page suivante / précédente. |
| `Ctrl+D` / `Ctrl+U` | Demi-page vers le bas / le haut. |
| `N` / `P` | Modification suivante / précédente. |
| `+` / `-` | Augmente / réduit le contexte. |
| `A` | Affiche toutes les lignes de contexte. |
| `=` | Rétablit le contexte par défaut. |
| `/` / `?` | Recherche vers l'avant / l'arrière. |
| `Échap` | Efface la recherche ou quitte. |
| `>` ou `.`, `<` ou `,` | Correspondance suivante / précédente. |
| `Y` | Copie la sélection. |
| `Ctrl+C` | Copie la sélection ou quitte. |
## Choix de fichiers (`kitten choose-files`)
| Touche | Action |
| --- | --- |
| Texte | Filtre la liste. |
| `Entrée` | Choisit le fichier sélectionné. |
| `Tab` | Entre dans le répertoire sélectionné. |
| `Maj+Tab` | Remonte d'un répertoire. |
| `Ctrl+Entrée` | Choisit le répertoire courant (ou saisit un nom de fichier en mode sauvegarde). |
| `Alt+Entrée` | Modifie le nom du fichier sélectionné. |
| `Maj+Entrée` | Ajoute ou retire le fichier de la sélection multiple. |
| `Ctrl+clic` / `Alt+clic` | Ajoute un fichier / sélectionne une plage à la souris. |
Les raccourcis de cette interface se redéfinissent dans
`~/.config/kitty/choose-files.conf`.
## Thèmes et polices
`kitten themes` et `kitten choose-fonts` se pilotent au clavier : tapez quelques
lettres pour filtrer, `Entrée` valide la famille ou le thème, `R` affine la
police régulière dans `choose-fonts`. Le détail figure dans leurs pages de
documentation.
## Personnaliser un raccourci
Les raccourcis globaux se redéfinissent dans `~/.config/kitty/kitty.conf` :
```conf
# Remplacer l'ouverture du gestionnaire de fichiers
map ctrl+shift+e launch --type=overlay kitten file-manager
# Rétablir l'ouverture des URLs sur Ctrl+Shift+E
map ctrl+shift+e open_url_with_hints
# Choisir d'autres touches pour l'historique
map kitty_mod+alt+h paste_from_clipboard_history
map kitty_mod+alt+g search_clipboard_history
```
La configuration est rechargée automatiquement, ou manuellement avec
`Ctrl+Shift+F5`. Une touche peut aussi être retirée en la mappant sur rien :
`map ctrl+shift+e`.
+1 -34
View File
@@ -9,8 +9,7 @@ supprime des entrées, et ouvre les fichiers dans l'éditeur.
Ce document décrit tout le cycle de vie du projet : récupérer le code, compiler, Ce document décrit tout le cycle de vie du projet : récupérer le code, compiler,
lancer, utiliser l'explorateur, tester, construire le paquet Arch et dépanner. lancer, utiliser l'explorateur, tester, construire le paquet Arch et dépanner.
`DEV.md` reste le guide de développement condensé, `README.asciidoc` est le `DEV.md` reste le guide de développement condensé, `README.asciidoc` est le
README d'origine de kitty et `RACCOURCIS-CLAVIER.md` liste tous les raccourcis README d'origine de kitty.
actifs par défaut, sans configuration.
## Contenu de la branche `feat/file-manager-panel` ## Contenu de la branche `feat/file-manager-panel`
@@ -299,38 +298,6 @@ réaffecte `_branch`) :
_branch=feat/file-manager-panel _branch=feat/file-manager-panel
``` ```
### Publication automatique
`version`, à la racine, est la source de vérité des releases. Il suit la version
du fork FWS (`0.1.17`), pas la version amont de kitty embarquée dans le paquet :
c'est elle qui nomme le tag, la release et le paquet
`fws-kitty-<version>-<rel>`. Il doit rester égal à `pkgver` dans
`packaging/PKGBUILD` et à la version affichée par `fws-kitty`
(`tools/cli/help.go`, `kitty/launcher/main.c`) ; `packaging/check-version.sh`
vérifie l'ensemble, ainsi que `_kittyver` du `PKGBUILD` contre
`kitty/constants.py`, et échoue sinon. Un push sur `main` qui modifie `version`
déclenche
`.gitea/workflows/package.yml`, qui compile le paquet une seule fois
(`makepkg`, seul build), lance lint, `go vet`, tests et smoke test sur cet
arbre, puis crée la release Gitea `v<version>` avec le paquet en pièce jointe
et l'envoie à `repo.laxacube.ch`. `.gitea/workflows/ci.yml` rejoue les mêmes
contrôles sur chaque PR et chaque push sur `main` qui ne modifie pas que
`version`.
Pour reconstruire la même version du fork (correctif de packaging), incrémentez
`pkgrel` dans `packaging/PKGBUILD` puis lancez le workflow à la main
(*Actions → Release → Run workflow*) : le paquet `0.1.8-2` remplace alors le
`0.1.8-1`. Une version déjà publiée n'est jamais réécrite avec un autre build :
si `repo.laxacube.ch` sert déjà ce nom de paquet, le workflow s'arrête sans
republier (relancer une release est donc sans effet et ne fait pas échouer la
CI) ; pour publier un build différent, incrémentez `pkgrel`, sinon les caches
(CDN, pacman) servent un fichier qui ne correspond plus à la base. Une nouvelle version du fork demande `version`,
`pkgver` et les deux front-ends, avec `pkgrel=1` ; pour suivre une nouvelle version de kitty, mettre
à jour `_kittyver` et `kitty/constants.py`. La publication vers
`repo.laxacube.ch` utilise le
secret `REPO_TOKEN` du dépôt, la release Gitea le secret `RELEASE_TOKEN` ; sans
`REPO_TOKEN` la release est créée mais le dépôt pacman n'est pas mis à jour.
La publication dans un dépôt pacman (`repo-add`, configuration client, La publication dans un dépôt pacman (`repo-add`, configuration client,
automatisation) est détaillée dans `packaging/README.md`. automatisation) est détaillée dans `packaging/README.md`.
-30
View File
@@ -1,30 +0,0 @@
# docCours — FWS-Kitty
Dossier de rendu du binôme (*Damien Rochat* + *Gianmarco Ruberti*) pour le projet
**FWS-Kitty**, le fork FWS du terminal kitty.
## Contenu
| Fichier | Rôle |
| --- | --- |
| [`plan-ci-cd.md`](plan-ci-cd.md) | **Document principal** : plan CI/CD complet (objectifs, analyse technique, conception du pipeline, suivi après mise en production, procédure de déploiement et de rollback) |
| [`methodologie-git-github.md`](methodologie-git-github.md) | Méthodologie de collaboration Git / GitHub : workflow, branches, revue de code, versionnage, commits |
| [`annexes/pipeline-ci.yml`](annexes/pipeline-ci.yml) | Ébauche de workflow CI/CD (syntaxe Actions, compatible Gitea `act_runner`) — non actif, à déplacer vers `.gitea/workflows/` après validation |
## Comment lire ce dossier
1. `plan-ci-cd.md` §1–2 : le contexte, les objectifs et les contraintes du projet.
2. §3 : les technologies, l'hébergement, les environnements, les variables et les secrets.
3. §4 : le pipeline étape par étape, avec les outils et les feedbacks attendus.
4. §5 : le suivi en production (monitoring, alertes, amélioration continue).
5. §6 : la synthèse des livrables et les procédures de déploiement / rollback.
6. `methodologie-git-github.md` pour la partie collaboration (workflow Git, revue, versionnage).
7. `annexes/pipeline-ci.yml` pour la traduction concrète du pipeline en configuration.
## État du dépôt
Le dépôt ne contient aujourd'hui **aucune configuration CI** (pas de
`.github/workflows/`, `.gitea/workflows/`, `.gitlab-ci.yml` ni `Jenkinsfile`) :
tous les contrôles (`./test.py`, `go test`, `ruff`, `./dev.sh build`,
`makepkg`) sont manuels. Les documents de ce dossier décrivent le pipeline
cible et l'ordre de mise en œuvre (§7 du plan).
-291
View File
@@ -1,291 +0,0 @@
# Ébauche du pipeline CI/CD de FWS-Kitty.
#
# Ce fichier n'est PAS actif : il vit dans docCours/ pour être relu avant mise
# en service. Pour l'activer, le déplacer vers .gitea/workflows/ci.yml (Gitea
# act_runner accepte la syntaxe GitHub Actions utilisée ici).
#
# Hypothèses :
# - runner act_runner avec accès à Docker, étiquettes [self-hosted, linux, x64]
# - image de build préconstruite : fws/kitty-build:latest (Arch + deps système)
# - caches persistants montés : /cache/kitty (ccache, Go, bundle deps)
name: CI
on:
pull_request:
push:
branches: [main]
tags: ['v*']
schedule:
- cron: '0 3 * * *' # nightly : sanitizers + réaudit
workflow_dispatch:
concurrency:
group: ci-${{ github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
env:
BUILD_IMAGE: fws/kitty-build:latest
CACHE_ROOT: /cache/kitty
CCACHE_DIR: /cache/kitty/ccache
GOCACHE: /cache/kitty/go-build
GOMODCACHE: /cache/kitty/go-mod
KITTY_DISABLE_WAYLAND: '1'
CI: 'true'
jobs:
# ---------------------------------------------------------------------------
# 0. Hygiène : convention de commits et fichiers interdits
# ---------------------------------------------------------------------------
hygiene:
runs-on: [self-hosted, linux, x64]
container: { image: 'fws/kitty-lint:latest' }
steps:
- uses: actions/checkout@v4
with: { fetch-depth: 0 }
- name: Check whitespace and conflict markers
run: git diff --check "${{ github.event.pull_request.base.sha || 'HEAD~1' }}" HEAD
- name: Validate commit messages (Conventional Commits)
run: |
base="${{ github.event.pull_request.base.sha || 'HEAD~1' }}"
git log --format=%s "$base"..HEAD | while read -r subject; do
echo "$subject" | grep -Eq \
'^(feat|fix|docs|style|refactor|perf|test|build|ci|chore|revert)(\([a-z0-9./-]+\))?!?: .{1,72}$' \
|| { echo "::error::Invalid commit subject: $subject"; exit 1; }
done
- name: Reject build artifacts and secrets
run: |
tracked="$(git ls-files)"
bad="$(echo "$tracked" | grep -E '\.pkg\.tar\.zst$|(^|/)(dependencies|build|\.venv)/|_generated\.go$|^\.env')" || true
if [ -n "$bad" ]; then echo "::error::Artifacts must not be tracked:"; echo "$bad"; exit 1; fi
# ---------------------------------------------------------------------------
# 1. Qualité : lint, format, typage
# ---------------------------------------------------------------------------
lint:
runs-on: [self-hosted, linux, x64]
container: { image: 'fws/kitty-lint:latest' }
steps:
- uses: actions/checkout@v4
- run: ruff check --output-format=github .
- run: ruff format --check .
- run: gofmt -s -l tools kittens bypy gen | tee /tmp/fmt.txt && test ! -s /tmp/fmt.txt
# go vet exige le code généré : on limite aux paquets autonomes en PR rapide
- run: go vet ./kittens/file_manager/ ./tools/... ./bypy/...
- run: staticcheck ./kittens/file_manager/ ./tools/... ./bypy/...
- name: Type check Python
run: ./dev.sh build && ./test.py type-check
# ---------------------------------------------------------------------------
# 2. Audit : vulnérabilités, dépendances, secrets, SBOM
# ---------------------------------------------------------------------------
audit:
runs-on: [self-hosted, linux, x64]
container: { image: 'fws/kitty-lint:latest' }
steps:
- uses: actions/checkout@v4
- name: Go vulnerabilities
run: govulncheck ./... | tee /tmp/govuln.txt
- name: Python doc dependencies
run: pip-audit -r docs/requirements.txt
- name: Secret scan
run: gitleaks detect --no-git --redact -v
- name: SBOM
run: syft dir:. -o spdx-json=sbom.spdx.json
- uses: actions/upload-artifact@v4
with: { name: sbom, path: sbom.spdx.json, retention-days: 90 }
# ---------------------------------------------------------------------------
# 3. Build : C + code généré + kittens + docs
# ---------------------------------------------------------------------------
build:
needs: [lint]
runs-on: [self-hosted, linux, x64]
container:
image: 'fws/kitty-build:latest'
options: --user builder
steps:
- uses: actions/checkout@v4
- name: Restore dependency bundle
run: |
test -x dependencies/linux-amd64/bin/python || ./dev.sh deps
- name: Build
run: |
start=$(date +%s)
./dev.sh build
echo "BUILD_SECONDS=$(( $(date +%s) - start ))" >> "$GITHUB_ENV"
- name: Smoke test binaries
run: |
./kitty/launcher/kitty --version
./kitty/launcher/kitten --version
- name: Build documentation
run: |
python -m venv .docs-venv
.docs-venv/bin/pip install --disable-pip-version-check -q -r docs/requirements.txt
PATH="$PWD/.docs-venv/bin:$PATH" make -C docs html FAIL_WARN=1
- uses: actions/upload-artifact@v4
with:
name: kitty-build
path: |
kitty/launcher/kitty
kitty/launcher/kitten
docs/_build/html
retention-days: 7
- name: Report build duration
run: echo "Build completed in ${BUILD_SECONDS}s"
# ---------------------------------------------------------------------------
# 4. Tests : suite Python + Go sous serveur X virtuel
# ---------------------------------------------------------------------------
test:
needs: [build]
runs-on: [self-hosted, linux, x64]
container:
image: 'fws/kitty-build:latest'
options: --user builder
steps:
- uses: actions/checkout@v4
- uses: actions/download-artifact@v4
with: { name: kitty-build, path: . }
- name: Go tests (file manager kitten)
run: go test --tags testing ./kittens/file_manager/
- name: Full suite
run: xvfb-run -a ./test.py
- name: Leak/UB check
if: github.event_name == 'schedule'
run: make asan && xvfb-run -a ./test.py --module kittens/file_manager
# ---------------------------------------------------------------------------
# 5. Paquet Arch : build, signature, test d'installation
# ---------------------------------------------------------------------------
package:
needs: [test]
runs-on: [self-hosted, linux, x64]
container:
image: 'fws/kitty-build:latest'
options: --user builder
outputs:
pkgver: ${{ steps.version.outputs.pkgver }}
pkgrel: ${{ steps.version.outputs.pkgrel }}
steps:
- uses: actions/checkout@v4
- name: Derive version from tag
id: version
run: |
if [ "${GITHUB_REF_TYPE}" = "tag" ]; then
echo "pkgver=${GITHUB_REF_NAME#v}" >> "$GITHUB_OUTPUT"
else
echo "pkgver=$(sed -n 's/^pkgver=//p' packaging/PKGBUILD)" >> "$GITHUB_OUTPUT"
fi
echo "pkgrel=$(sed -n 's/^pkgrel=//p' packaging/PKGBUILD)" >> "$GITHUB_OUTPUT"
- name: Build package
run: |
cd packaging
sed -i "s/^pkgver=.*/pkgver=${{ steps.version.outputs.pkgver }}/;s/^pkgrel=.*/pkgrel=${{ steps.version.outputs.pkgrel }}/" PKGBUILD
makepkg -f --nodeps
repo-add fws-kitty.db.tar.gz fws-kitty-*.pkg.tar.zst
namcap fws-kitty-*.pkg.tar.zst || true
- name: Sign (production only)
if: startsWith(github.ref, 'refs/tags/v')
env:
GPG_PRIVATE_KEY: ${{ secrets.GPG_PRIVATE_KEY }}
GPG_PASSPHRASE: ${{ secrets.GPG_PASSPHRASE }}
run: |
printf '%s' "$GPG_PRIVATE_KEY" | base64 -d | gpg --batch --import
cd packaging
for f in fws-kitty-*.pkg.tar.zst; do
gpg --batch --pinentry-mode loopback --passphrase "$GPG_PASSPHRASE" \
--detach-sign --no-armor "$f"
done
repo-add --sign --key <FWS_KEY_ID> fws-kitty.db.tar.gz fws-kitty-*.pkg.tar.zst
- name: Install test in a clean container
run: |
docker run --rm -v "$PWD/packaging:/pkgs:ro" archlinux:base-devel \
sh -c 'pacman -U --noconfirm /pkgs/fws-kitty-*.pkg.tar.zst && kitty --version && kitten file-manager --help'
- uses: actions/upload-artifact@v4
with:
name: arch-package
path: |
packaging/fws-kitty-*.pkg.tar.zst*
packaging/fws-kitty.db.tar.gz*
retention-days: 30
# ---------------------------------------------------------------------------
# 6a. Staging : automatique sur main
# ---------------------------------------------------------------------------
deploy-staging:
if: github.ref == 'refs/heads/main' && github.event_name == 'push'
needs: [package]
runs-on: [self-hosted, linux, x64]
environment: staging
steps:
- uses: actions/download-artifact@v4
with: { name: arch-package, path: pkgs }
- name: Publish to fws-testing repository
env:
SSH_KEY: ${{ secrets.REPO_DEPLOY_SSH_KEY }}
HOST: ${{ secrets.REPO_DEPLOY_HOST }}
USER: ${{ secrets.REPO_DEPLOY_USER }}
run: |
install -m 600 /dev/null ~/.ssh/deploy && printf '%s' "$SSH_KEY" > ~/.ssh/deploy
rsync -av -e "ssh -i ~/.ssh/deploy -o StrictHostKeyChecking=yes" \
pkgs/ "$USER@$HOST:/srv/pacman/fws/testing/x86_64/"
- name: Verify published package
run: |
docker run --rm archlinux:base-devel sh -c \
'printf "[fws-testing]\nServer = %s\nSigLevel = Optional\n" "${{ vars.TESTING_REPO_URL }}" >> /etc/pacman.conf && \
pacman -Syu --noconfirm fws-kitty && kitty --version'
# ---------------------------------------------------------------------------
# 6b. Production : tag vX.Y.Z + approbation manuelle
# ---------------------------------------------------------------------------
release:
if: startsWith(github.ref, 'refs/tags/v')
needs: [package]
runs-on: [self-hosted, linux, x64]
environment: production # required_reviewers : 1 mainteneur
steps:
- uses: actions/checkout@v4
- uses: actions/download-artifact@v4
with: { name: arch-package, path: pkgs }
- name: Publish to stable repository
env:
SSH_KEY: ${{ secrets.REPO_DEPLOY_SSH_KEY_PROD }}
HOST: ${{ secrets.REPO_DEPLOY_HOST }}
USER: ${{ secrets.REPO_DEPLOY_USER }}
run: |
install -m 600 /dev/null ~/.ssh/deploy && printf '%s' "$SSH_KEY" > ~/.ssh/deploy
rsync -av -e "ssh -i ~/.ssh/deploy -o StrictHostKeyChecking=yes" \
pkgs/ "$USER@$HOST:/srv/pacman/fws/x86_64/"
- name: Publish Gitea release
env:
TOKEN: ${{ secrets.GITEA_TOKEN }}
run: |
curl -sS -X POST "$GITEA_API/repos/$GITHUB_REPOSITORY/releases" \
-H "Authorization: token $TOKEN" \
-F tag_name="$GITHUB_REF_NAME" \
-F name="$GITHUB_REF_NAME" \
-F body="$(sed -n "/^## \\[$GITHUB_REF_NAME\\]/,/^## \\[/p" CHANGELOG.rst | head -n -1)" \
-F attachment=@pkgs/fws-kitty-*.pkg.tar.zst
- name: Verify production install
run: |
docker run --rm archlinux:base-devel sh -c \
'printf "[fws]\nServer = %s\nSigLevel = Required DatabaseOptional\n" "${{ vars.PROD_REPO_URL }}" >> /etc/pacman.conf && \
pacman -Syu --noconfirm fws-kitty && kitty --version'
# ---------------------------------------------------------------------------
# 7. Notification : un échec doit toujours dire quoi faire
# ---------------------------------------------------------------------------
notify:
if: always()
needs: [lint, audit, build, test, package]
runs-on: [self-hosted, linux, x64]
steps:
- name: Send status to team webhook
run: |
curl -sS -X POST "${{ secrets.NOTIFY_WEBHOOK_URL }}" \
-H 'Content-Type: application/json' \
-d "{\"content\":\"CI ${{ job.status }} on ${{ github.repository }}@${{ github.sha }} (${{ github.ref_name }})\"}"
-216
View File
@@ -1,216 +0,0 @@
# Méthodologie de collaboration Git / GitHub
| Élément | Valeur |
| --- | --- |
| Projet de référence | **FWS-Kitty** (fork FWS de kitty) |
| Binôme | *Damien Rochat* + *Gianmarco Ruberti* |
| Date / statut | Novembre 2026 — version 0.50.0 |
> Document de référence : il décrit **comment nous travaillerions** en contexte professionnel. Aucune manipulation Git réelle n'est effectuée ; les commandes illustrent la méthode.
## 1. Projet de référence
FWS-Kitty : fork du terminal kitty auquel nous ajoutons un panneau de gestion de fichiers (`kittens/file_manager/`). Représentatif de notre futur quotidien :
- **Dépôt existant et volumineux** (C, Python, Go, docs Sphinx) : on s'y insère, on ne réécrit pas.
- **Travail parallèle** sur des zones distinctes : interface Go, options Python, docs, packaging Arch, CI.
- **Revue réellement utile** : le code touche au shell (suppression de fichiers, `cd`).
- **Contrôles automatisables** : `./test.py`, `go test ./kittens/file_manager/`, `ruff check`, `./dev.sh build`, `./dev.sh docs`.
- Le choix du projet doit être **validé par l'enseignant** ; sinon seules les commandes changent.
## 2. a) Organisation
| Rôle | Responsabilité principale | Qui |
| --- | --- | --- |
| Mainteneur / intégrateur | protège `main`, arbitre, valide les fusions, tient `CHANGELOG` et tags | binôme A |
| Développeur·se / relecteur·se | développe, relit toutes les PR | binôme B |
| Responsable qualité | surveille CI, lint, tests, régressions | alternance |
| Responsable documentation | vérifie la mise à jour de `README.md` / `docs/` | alternance |
Règle d'or : **celui qui écrit le code ne valide jamais seul sa PR**. Découpage **par fonctionnalité verticale** (Go → Python → docs), jamais par couche technique. **Une issue = un périmètre = une branche = une PR**, sinon on scinde.
| Canal | Usage | Fréquence |
| --- | --- | --- |
| Issues / PR GitHub | canal **officiel** de toute décision technique | continu |
| Discussions | choix d'architecture, questions ouvertes | au besoin |
| Discord privé | synchronisation rapide, blocages | quotidien |
| Visio 15 min | hier / aujourd'hui / bloqué | 1–2×/jour |
| Bilan d'itération | reste à faire, Kanban, ajustement de la méthode | hebdomadaire |
**Traçabilité** : une décision prise à l'oral est retranscrite dans l'issue ou la PR avant application — « si ce n'est pas écrit sur GitHub, ça n'existe pas ».
| Besoin | Outil | Justification |
| --- | --- | --- |
| Suivi des tâches | **GitHub Projects** (Kanban) | une issue = une carte, rien à administrer |
| Doc technique | Markdown versionné (`docs/`, `README.md`) | évolue dans la même PR que le code |
| CI | **GitHub Actions** (ou Gitea `act_runner` si le dépôt y vit) | natif, pas de serveur |
| Qualité | `ruff`, `gofmt`/`go vet`, `./test.py`, hooks `pre-commit` | déjà dans le dépôt |
*Écartés* : Jira et Trello (outil + double saisie pour un binôme).
**Kanban** : `Backlog` -> `À faire` -> `En cours` (**1 carte max/personne**) -> `En revue` -> `Terminé`. Gabarit d'issue obligatoire (contexte, attendu, critères d'acceptation, labels). Labels : `type: feat|fix|docs|chore`, `prio:`, `zone: go|python|docs|packaging|ci`, `état: bloqué`. Lien bidirectionnel issue <-> PR <-> commit. Décisions structurantes consignées en issue `décision` ou en ADR (`docs/adr/NNN-titre.md`).
## 3. b) Workflow Git
**GitHub Flow (trunk-based simplifié)** : une seule branche longue (`main`, toujours déployable), branches de travail de **1 à 3 jours**, PR obligatoire.
| Critère | GitHub Flow (retenu) | Git Flow | Feature Branch pur |
| --- | --- | --- | --- |
| Complexité | faible | élevée | faible |
| Adapté au binôme | oui | non (`develop` = goulot) | oui mais sans garde-fou |
| Fréquence d'intégration | élevée, conflits rares | faible, gros merges | moyenne |
| Livraison | continue, tag sur `main` | par release planifiée | au cas par cas |
Git Flow a été conçu pour des équipes nombreuses livrant des versions planifiées ; à deux, sa `develop` n'ajoute que de la synchronisation. Le Feature Branch pur ne protège pas `main`.
| Branche | Rôle | Durée | Protection |
| --- | --- | --- | --- |
| `main` | référence, toujours compilable et testée, c'est elle qui est empaquetée | permanente | PR + 1 approbation + CI verte, pas de push direct ni force-push |
| `feat/<desc>` | fonctionnalité | ≤ 3 j | aucune, CI avant PR |
| `fix/<desc>`, `docs/<desc>` | correctif, documentation | ≤ 1 j | — |
| `chore/`, `ci/`, `refactor/` | maintenance, sans changement de comportement | ≤ 2 j | — |
| `hotfix/<desc>` | correction urgente d'une version livrée | heures | part de `main`, puis tag `PATCH` |
| `release/x.y.z` | uniquement si une version doit être gelée | jours | merge commit |
Nommage `type/description`, kebab-case, en anglais, décrivant **l'intention** (`feat/file-manager-create-entry`). Interdits : prénom, date, `test`, `wip`, majuscules. Branche supprimée après fusion.
```sh
git switch main && git pull --ff-only
git switch -c feat/file-manager-create-entry
git add kittens/file_manager/main.go
git commit -m "feat(file-manager): add file creation from status line"
git fetch origin && git rebase origin/main # branche perso uniquement
git push -u origin feat/file-manager-create-entry
gh pr create --fill --reviewer <binôme> # PR + CI verte
# fusion en "Squash and merge", puis suppression de la branche
```
Fusions : **squash and merge** pour les fonctionnalités (un commit propre par PR), merge commit pour `release/*` et `hotfix/*`, rebase-and-merge interdit sur `main`.
**Protection de `main`** : PR obligatoire (mainteneurs inclus), 1 approbation avec invalidation après nouveau push, statuts `lint` / `tests` / `build` requis, branche à jour et conversations résolues, force-push et suppression interdits, commits signés, `CODEOWNERS` sur `kittens/file_manager/`, `packaging/`, `docs/`.
**Versionnage SemVer 2.0.0** (`MAJEUR.MINEUR.CORRECTIF`, tags `vX.Y.Z`) : `MAJEUR` = rupture (option renommée, config illisible), `MINEUR` = fonctionnalité compatible, `CORRECTIF` = correction. Pré-versions `v0.51.0-rc.1`. Tag **annoté et signé** sur `main` (`git tag -s v0.51.0 -m "..."`), `CHANGELOG` mis à jour dans la PR de release, release créée depuis le tag. Une version livrée ne se réécrit jamais : on publie un `PATCH`.
**Conventional Commits 1.0.0** : `<type>(<portée>): <description impérative>` en **anglais**, ≤ 72 caractères, corps expliquant le *pourquoi*.
| Type | Usage | Type | Usage |
| --- | --- | --- | --- |
| `feat` | fonctionnalité visible | `test` | tests |
| `fix` | correction de bug | `build` | build, dépendances, packaging |
| `docs` | documentation | `ci` | intégration continue |
| `style` | formatage | `chore` | tâches annexes |
| `refactor` | réécriture interne | `perf` | performance |
| `revert` | annulation | — | — |
```
feat(file-manager): add directory creation with shift+n
fix(file-manager): keep cd working when panel runs in a dock
ci: run go tests for the file manager kitten
```
Un commit = un changement cohérent qui compile et dont les tests passent ; impératif présent ; pas de `wip` ni `update` ; référence d'issue (`Fixes #42`) ; breaking change = `feat(config)!` + pied `BREAKING CHANGE:`. Vérifié par `.gitmessage` et un hook `commit-msg` (Commitlint).
## 4. c) Revue de code
1. **Draft PR** dès le premier commit poussé : CI lancée, l'autre suit l'avancement.
2. **PR prête** : gabarit rempli (contexte, issue liée, changements, comment tester), relecteur assigné, labels.
3. **CI verte exigée** avant toute relecture approfondie.
4. **Revue sous 24 h ouvrées** : *Approve*, *Request changes* (bloquant, justifié) ou *Comment* (non bloquant).
5. **Corrections en commits supplémentaires**, sans force-push pendant la revue (diff incrémental lisible).
6. **Squash and merge**, suppression de la branche, carte en `Terminé`, vérification que `main` reste verte.
| Contexte | Approbations |
| --- | --- |
| Binôme (notre cas) | **1** par l'autre + CI verte (l'auteur ne peut pas s'auto-approuver) |
| Équipe de 3 à 5 | 2 |
| Équipe > 5 / code critique | 2 dont un `CODEOWNER` |
| `hotfix` urgent | 1, rétro-revue sous 48 h |
La CI ne remplace pas le relecteur et inversement : une PR approuvée dont un nouveau commit casse la CI repasse en revue.
**Definition of Done** : issue liée et critères couverts · **CI verte** (`ruff`, `gofmt`/`go vet`, `go test ./kittens/file_manager/`, `./test.py`, `./dev.sh build`) · relue et approuvée, commentaires résolus · Conventional Commits en anglais · **aucun fichier parasite** (`*_generated.go`, `dependencies/`, `.env`, artefacts) · doc et aide des options à jour · tests ajoutés (cas limites : caractères larges, chemins vides, permissions) · pas de régression sur les erreurs (répertoire non vide, fichier non inscriptible) · portée respectée · branche à jour, sans conflit · performance : pas de boucle coûteuse dans le rendu · sécurité : aucun shell concaténé non échappé, aucun secret.
**Bonnes pratiques** : PR ≤ 400 lignes modifiées (au-delà, le taux de détection s'effondre) · relire le code, pas la personne · commentaires actionnables et préfixés `[bloquant]`, `[suggestion]`, `[question]`, `[nit]` · on propose, l'auteur applique · test local quand le changement est subtil · pas de « LGTM » sec : dire ce qui a été vérifié.
## 5. d) Collaboration
| Action | Fréquence | Raison |
| --- | --- | --- |
| Commit | 3 à 10/jour, 50–200 lignes | point de sauvegarde, retour arrière ciblé |
| Push | ≥ 1×/demi-journée et en fin de journée | sauvegarde, CI lancée tôt, travail visible |
| PR | dès que c'est testable, même en brouillon | relecture précoce, conflits détectés tôt |
| Sync `main` | chaque matin + après chaque fusion | branches courtes = conflits rares |
**Conflits — prévention** : branches courtes et périmètre étroit ; `rebase origin/main` quotidien ; ne pas éditer `CHANGELOG.md` ni les fichiers générés dans deux branches ; formateurs et `.gitattributes`/`.editorconfig` pour éviter les faux conflits. **Résolution** : comprendre les deux versions (`git log --merge -p`), résoudre, `git add` puis `git rebase --continue` (`--abort` en cas de doute), tester puis `git push --force-with-lease` (jamais `--force`) ; **jamais de rebase sur une branche partagée** (on y fusionne `main`) ; au-delà de 15 min, on s'appelle. Des conflits récurrents signalent un mauvais découpage, pas seulement un mauvais merge.
**Traçabilité** : la chaîne **issue -> branche -> commit -> PR -> tag** doit permettre de retrouver chaque décision. Issue = le *quoi* et le *pourquoi* ; branche = l'intention + numéro d'issue si naturel ; commit = Conventional Commits avec le *pourquoi* ; PR = description, revue, décisions actées ; ADR pour les choix structurants (immuables) ; `CHANGELOG` par version ; labels et board pour l'état. Aucun message ne mentionne l'outil ou l'assistant utilisé.
| Niveau | Contrôle | Quand |
| --- | --- | --- |
| Local | hooks `pre-commit` (ruff, gofmt, détection de secrets), `.gitmessage` | avant chaque commit |
| Branche | CI : lint, tests, build | à chaque push |
| PR | gabarit rempli, checklist cochée, CI obligatoire | avant revue |
| Revue | relecture humaine, test local, 1 approbation | avant fusion |
| `main` | CI post-fusion, tag SemVer, release notes | à chaque fusion notable |
```yaml
# .gitea/workflows/ci.yml (ou .github/workflows/ci.yml)
on: { pull_request: , push: { branches: [main] } }
jobs:
lint: { steps: [ruff check ., gofmt -l . && go vet ./kittens/file_manager/] }
tests: { steps: [go test ./kittens/file_manager/, ./test.py type-check] }
build: { steps: [./dev.sh deps && ./dev.sh build] }
```
Hygiène : `.gitignore` à la racine, jamais de secrets ni de `git add .` aveugle, pas de force-push sur une branche partagée, commits signés. Chaque `TODO` ou contournement devient une issue `dette`, jamais un commentaire orphelin.
**Rythme** : point quotidien de 15 min · revue croisée systématique · arrêt propre (branche poussée, carte à jour, état décrit en commentaire si incomplet) · pas de travail « fantôme » d'une semaine en local · bilan d'itération et ajustement de ce document, qui est versionné.
## 6. Bilan du choix
**Avantages** : feedback en heures · `main` toujours livrable · conflits limités · traçabilité complète · connaissance partagée (pas de bus factor de 1) · coût d'outillage quasi nul · historique lisible (squash + Conventional Commits + SemVer) · transposable à 5–10 personnes.
| Limite | Parade |
| --- | --- |
| Une seule approbation = un angle mort | checklist, CI stricte, test local, 2 approbations dès une 3ᵉ personne |
| Pas de `develop` (pas de zone de stabilisation) | branches `release/*` ponctuelles |
| La revue peut bloquer | réponse < 24 h, PR courtes, `Draft PR` |
| GitHub Flow exige des branches courtes | règle des 3 jours, indicateur « âge des branches » |
| Squash = perte de granularité | commits soignés quand même, merge commit pour `release/*` |
| Rôles cumulés (petit effectif) | rôles tournants + checklist non négociable |
*Écartés* : **Git Flow** (surdimensionné, merges massifs), **Feature Branch sans PR** (aucune garantie sur `main`), **trunk-based avec push direct** (trop risqué pour du code qui touche au shell).
## 7. Récapitulatif
1. Une seule branche longue, `main`, protégée et toujours verte.
2. Branches courtes `type/description` (≤ 3 jours).
3. Une issue = une branche = une PR, périmètre strict.
4. GitHub Flow, fusion en squash and merge.
5. Conventional Commits en anglais, un commit = un changement cohérent.
6. SemVer, tags signés, `CHANGELOG`.
7. PR obligatoire : gabarit, CI verte, checklist.
8. 1 approbation par le binôme (2 dès 3 personnes).
9. Push 2×/jour, rebase quotidien, conflits résolus à deux.
10. Toute décision est écrite sur GitHub, sinon elle n'existe pas.
## 8. Annexes
```
[ ] branche à jour, CI verte
[ ] diff < ~400 lignes, sinon découpé
[ ] issue liée, description remplie (contexte, tests)
[ ] propre diff relu (git diff main...HEAD)
[ ] aucun fichier généré, secret ou artefact versionné
[ ] doc et tests à jour
```
```sh
git switch -c feat/<sujet>
git fetch origin && git rebase origin/main
git log --oneline --graph --decorate
git diff main...HEAD
git rebase -i origin/main
git push --force-with-lease
git tag -s v0.51.0 -m "release"
```
-142
View File
@@ -1,142 +0,0 @@
# Plan CI/CD — FWS-Kitty
| Élément | Valeur |
| --- | --- |
| Projet | **FWS-Kitty** — fork FWS de kitty (`0.50.0`, Gitea `FWS/FWS-Kitty`) |
| Binôme | *Damien Rochat* + *Gianmarco Ruberti* — Novembre 2026 |
| Livrables | paquet Arch `fws-kitty` (dépôt pacman, base de l'ISO FWS) + documentation Sphinx |
| Documents liés | `methodologie-git-github.md`, `annexes/pipeline-ci.yml` |
> **Constat** : aucune CI dans le dépôt (pas de `.github/`, `.gitea/`, `.gitlab-ci.yml` ni `Jenkinsfile`) ; tous les contrôles sont manuels. Ce plan décrit le pipeline cible.
---
## 1. a) Objectifs
| Axe | Décision |
| --- | --- |
| **Fréquence** | CI sur chaque push/PR ; **staging automatique** à chaque fusion sur `main` (1–3×/semaine) ; **production sur tag `vX.Y.Z` + approbation manuelle** (toutes les 2–4 semaines, ou `hotfix`) ; build ASAN nightly |
| **Rollback** | Le dépôt pacman conserve les **3 dernières versions** ; retrait d'une version fautive par `repo-remove` (jamais de suppression d'artefact) ; tags immuables, artefact reconstructible ; **RTO ≤ 30 min, RPO = 0** |
| **Sécurité / conformité** | GPL-3.0 (sources publiées, `LICENSE` dans le paquet) ; **paquets et base `repo-add` signés GPG** ; aucun secret versionné, secrets scopés par environnement ; audit des dépendances à chaque PR ; SBOM + SHA-256 par release ; `main` protégée (PR + 1 approbation + CI verte) |
| **Performance** | Lint/audit ≤ 3 min ; **pipeline PR ≤ 20 min** ; build ≤ 25 min (caches `ccache`/Go/bundle) ; release ≤ 45 min ; runner ≥ 4 vCPU / 8 Go |
| **Contraintes** | Linux x86_64 uniquement (`dev.sh` refuse Windows) ; **Arch obligatoire** pour `makepkg`, qui refuse `root` ; ~25 dépendances système ; bundle de dépendances téléchargé d'un hôte tiers **sans somme de contrôle** ; code Go généré avant `go vet` ; `./test.py` exige un binaire compilé et un serveur X ; CI Gitea = runner `act_runner` à administrer |
---
## 2. b) Analyse technique
### Technologies et impact CI/CD
| Techno | Impact |
| --- | --- |
| **C** (cœur, `glfw/`, `glad/`, `3rdparty/`) | Étape de build la plus longue → image Arch pré-équipée, `ccache` ; `clang-format --dry-run --Werror` (`.clang-format`) ; ASAN/UBSAN via `make asan` en nightly |
| **Python ≥ 3.12** | `ruff check` + `ruff format --check` (`pyproject.toml`), `ty` via `./test.py type-check`, `unittest` dans `kitty_tests/` (90 fichiers) ; le bundle fournit son propre Python |
| **Go ≥ 1.26** | `gofmt -s -l`, `go vet`, `staticcheck` (`staticcheck.conf`), `go test --tags testing` ; caches `GOCACHE`/`GOMODCACHE` ; `go.sum` = surface d'audit |
| **Sphinx/Furo** (`docs/requirements.txt`) | Build docs avec `FAIL_WARN=1` ; **versions non figées** → à épingler |
| **`setup.py` / `bypy`** | `./dev.sh build` est le **seul point d'entrée valable** (génère `*_generated.go`, compile shaders via `slangc`) : la CI ne doit pas appeler `go build` seul |
| **`makepkg` / `repo-add`** | Conteneur Arch + utilisateur non-root ; `repo-add --sign` ; publication `rsync` |
| **Gitea** | CI via `act_runner` (syntaxe Actions) ; API pour releases ; webhooks de notification |
### Hébergement et sécurisation
| Composant | Choix et mesures |
| --- | --- |
| Source | Gitea auto-hébergé ; `main` protégée, commits signés, `CODEOWNERS` sur `kittens/file_manager/`, `packaging/`, `docs/` |
| Runner | VM Arch dédiée, runner privé ; **aucun secret exposé aux PR de forks** ; jeton courte durée ; image de build reconstruite chaque semaine |
| Dépôts pacman | Staging `fws-testing` et prod `fws` en HTTPS statique ; écriture par clé SSH dédiée ; **prod signée** et lue avec `SigLevel = Required DatabaseOptional` — le `SigLevel = Optional TrustAll` de `packaging/README.md` ne doit pas être repris en production |
| Clés / artefacts | Clé GPG FWS uniquement dans le job de production (passphrase, rotation annuelle) ; 3 dernières versions conservées + archive hors ligne ; journaux 90 jours |
### Environnements
| Env | Usage | Moyens | Cycle de vie |
| --- | --- | --- | --- |
| **dev** | développement local | Arch/WSL2/`Dockerfile.arch`, `./dev.sh` | permanent, par développeur |
| **test (CI)** | valider chaque commit | conteneur Arch jetable, `HOME`/XDG redirigés, `CI=true`, `xvfb-run` | éphémère |
| **staging** | paquet installable + ISO de test | dépôt `fws-testing`, VM Arch | auto sur `main`, conservé 30 j |
| **prod** | utilisateurs et ISO FWS | dépôt `fws` signé, releases Gitea | tag validé uniquement, immuable |
### Variables et secrets
Variables non sensibles : `CI=true`, `DEVELOP_ROOT`, `PKG_CONFIG_PATH`, `SLANGC` (posés par `dev.sh`), `GOCACHE`, `GOMODCACHE`, `CCACHE_DIR`, `SOURCE_DATE_EPOCH`, `PKGEXT=.pkg.tar.zst`, `MAKEFLAGS=-j4`, `DISPLAY=:99`, `KITTY_DISABLE_WAYLAND=1`, `PACMAN_REPO_URL`, `PKGVER`/`PKGREL`.
| Secret | Usage | Portée |
| --- | --- | --- |
| `GPG_PRIVATE_KEY` + `GPG_PASSPHRASE` | signature des paquets | **prod uniquement**, rotation annuelle |
| `REPO_DEPLOY_SSH_KEY` (×2) | écriture dépôts staging / prod | clés distinctes, trimestrielle |
| `GITEA_TOKEN` | release + artefacts | dépôt, portée `repo`, trimestrielle |
| `NOTIFY_WEBHOOK_URL` | notifications d'équipe | équipe |
| `GPG_KEY_ID`, `REPO_DEPLOY_HOST`/`_USER` | paramètres de publication | par environnement |
Règles : secrets masqués dans les logs (un secret affiché est tourné), scan `gitleaks` à chaque PR, aucune publication possible depuis une PR externe.
---
## 3. c) Pipeline
```
PR / push ─► 0 Hygiène ─► 1 Qualité ∥ 2 Audit ─► 3 Build ─► 4 Tests ─► 5 Paquet
│
main ─► 6a Staging (auto) ◄──────────────────────┤
tag v* ─► 6b Prod (approbation) ◄───────────────────┘
└─► 7 Monitoring
```
| # | Étape | Outils | Feedback |
| --- | --- | --- | --- |
| 0 | Hygiène | `git diff --check`, Commitlint (Conventional Commits), contrôle des artefacts versionnés (`*.pkg.tar.zst`, `dependencies/`, `*_generated.go`, `.env*`) | annotation sur le commit fautif, merge bloqué |
| 1 | Qualité | `ruff check` / `ruff format --check`, `./test.py type-check` (`ty`), `gofmt -s -l`, `go vet`, `staticcheck`, `clang-format`, `shellcheck` | annotations fichier:ligne + correctif suggéré |
| 2 | Audit | `govulncheck ./...`, `pip-audit -r docs/requirements.txt`, `osv-scanner`, `trivy`, `gitleaks`, `go-licenses` (GPL), `syft` (SBOM) | résumé CVE en PR, issue `sécurité` pour le non bloquant, alerte si critique avec correctif |
| 3 | Build | `./dev.sh deps` (bundle mirroré + empreinte), `./dev.sh build`, `make -C docs html FAIL_WARN=1`, smoke `kitty --version` | journal en artefact, durée vs médiane (+20 % = alerte) |
| 4 | Tests | `xvfb-run -a ./test.py` (Python + Go, 8 workers), `go test --tags testing ./kittens/file_manager/`, couverture, ASAN nightly | JUnit + résumé + 5 tests les plus lents, annotation sur l'échec |
| 5 | Paquet | `pkgver` depuis le tag, `makepkg -f --nodeps`, `gpg --detach-sign`, `repo-add --sign`, `namcap`, **installation réelle dans un conteneur Arch propre** (bloquant) | taille, dépendances, résultat d'installation |
| 6a | Staging (auto) | `rsync` + `pacman -Sy && kitty --version` depuis le dépôt publié | « staging prêt » + empreinte ; retrait auto de l'index si la vérification échoue |
| 6b | Prod (manuel) | approbation d'environnement, publication signée, release Gitea (paquet, SBOM, SHA-256) | release + notification + rappel de rollback |
Bonnes pratiques : `cancel-in-progress` sur PR ; jobs idempotents ; un échec indique toujours la cause et l'action ; `go vet` limité aux paquets autonomes en PR rapide, étendu après build en job complet ; un test intermittent crée une issue, pas un re-run en boucle.
---
## 4. d) Suivi après mise en production
| Forme | But |
| --- | --- |
| **Santé du paquet publié** (job quotidien) | `pacman -Syu fws-kitty` puis `kitty --version` dans un conteneur Arch propre : détecte un dépôt cassé, une signature invalide ou une casse due au rolling release Arch |
| **Métriques du pipeline** | durées, taux de succès, reprises : vérifier les objectifs du §1 |
| **Veille sécurité** | CVE sur les dépendances du paquet (harfbuzz, openssl, mesa) et sur le bundle |
Seuils d'alerte : succès `main` < 95 % sur 20 runs, pipeline PR p95 > 20 min, 1 échec d'installation prod, 1 CVE critique corrigeable, branche ouverte > 3 jours. **Pas de télémétrie embarquée** : le retour utilisateur passe par les issues, on n'ajoute pas de mouchard à un terminal. Amélioration continue : revue mensuelle du pipeline, post-mortem sans blâme, mesure avant toute optimisation, contrôles non bloquants promus en bloquants une fois la dette résorbée.
---
## 5. Livrables, déploiement et rollback
**Besoins** : feedback rapide et `main` verte, paquet signé testé avant publication, staging auto, prod validée, rollback ≤ 30 min, conformité GPL, traçabilité commit → artefact.
**Dépendances externes**
| Dépendance | Risque / parade |
| --- | --- |
| Bundle `download.calibre-ebook.com` (Python, Sphinx, pkg-config, polices) | aucune somme de contrôle → **mirrorer et vérifier l'empreinte** |
| Nerd Fonts `v3.5.1` | déjà épinglée par `sha256sums` ✔ |
| Dépôts Arch `core`/`extra` | rolling release → job de santé quotidien |
| Modules Go / PyPI | versions Go figées (audit) ; **`docs/requirements.txt` à épingler** |
| Gitea et serveur pacman | sauvegardes, artefacts archivés hors ligne |
**Pas de BDD, d'API ni de microservice** : le livrable est un binaire, aucune dépendance runtime réseau.
**Déploiement staging (automatique, après build + tests)**
```sh
cd packaging && makepkg -f --nodeps
repo-add fws-kitty.db.tar.gz fws-kitty-*.pkg.tar.zst
rsync -av fws-kitty.db* fws-kitty-*.pkg.tar.zst \
"$REPO_USER@$REPO_HOST:/srv/pacman/fws/testing/x86_64/"
# vérif : conteneur Arch propre, pacman -Sy fws-kitty && kitty --version
```
**Déploiement production (manuel)** : `main` verte + staging de la même version validé → `git tag -s vX.Y.Z` et push → **approbation de l'environnement `production`** → publication signée + release Gitea → vérification d'installation → notification.
**Rollback** : `sudo pacman -U /var/cache/pacman/pkg/fws-kitty-<version>-<rel>-x86_64.pkg.tar.zst`, ou côté dépôt `repo-remove` puis `repo-add --sign` sur les versions antérieures ; publier ensuite un `hotfix` (`PATCH`) et documenter l'incident.
**Mise en œuvre** : 0) mesurer les durées réelles et épingler les dépendances → 1) runner + image + lint/build → 2) tests complets + audit → 3) paquet + staging → 4) signature + prod + rollback testé → 5) monitoring. Actions immédiates : sortir les 4 `*.pkg.tar.zst` de `packaging/` du versionnement, remplacer `SigLevel = Optional TrustAll`, mirrorer le bundle.
**Annexes** : `annexes/pipeline-ci.yml` (workflow complet, non actif), `methodologie-git-github.md`, `README.md`.
+15 -30
View File
@@ -12,36 +12,21 @@ window manager. The keyboard controls (which are :ref:`all customizable
Scrolling Scrolling
~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~
========================== ======================= ========================= =======================
Action Shortcut Action Shortcut
========================== ======================= ========================= =======================
Line up :sc:`scroll_line_up` (also :kbd:`⌥+⌘+⇞` and :kbd:`⌘+↑` on macOS) Line up :sc:`scroll_line_up` (also :kbd:`⌥+⌘+⇞` and :kbd:`⌘+↑` on macOS)
Line down :sc:`scroll_line_down` (also :kbd:`⌥+⌘+⇟` and :kbd:`⌘+↓` on macOS) Line down :sc:`scroll_line_down` (also :kbd:`⌥+⌘+⇟` and :kbd:`⌘+↓` on macOS)
Page up :sc:`scroll_page_up` (also :kbd:`⌘+⇞` on macOS) Page up :sc:`scroll_page_up` (also :kbd:`⌘+⇞` on macOS)
Page down :sc:`scroll_page_down` (also :kbd:`⌘+⇟` on macOS) Page down :sc:`scroll_page_down` (also :kbd:`⌘+⇟` on macOS)
Top :sc:`scroll_home` (also :kbd:`⌘+↖` on macOS) Top :sc:`scroll_home` (also :kbd:`⌘+↖` on macOS)
Bottom :sc:`scroll_end` (also :kbd:`⌘+↘` on macOS) Bottom :sc:`scroll_end` (also :kbd:`⌘+↘` on macOS)
Previous shell prompt :sc:`scroll_to_previous_prompt` (see :ref:`shell_integration`) Previous shell prompt :sc:`scroll_to_previous_prompt` (see :ref:`shell_integration`)
Next shell prompt :sc:`scroll_to_next_prompt` (see :ref:`shell_integration`) Next shell prompt :sc:`scroll_to_next_prompt` (see :ref:`shell_integration`)
Browse scrollback in less :sc:`show_scrollback` Browse scrollback in less :sc:`show_scrollback`
Browse last cmd output :sc:`show_last_command_output` (see :ref:`shell_integration`) Browse last cmd output :sc:`show_last_command_output` (see :ref:`shell_integration`)
Search scrollback in less :sc:`search_scrollback` (also :kbd:`⌘+F` on macOS) Search scrollback in less :sc:`search_scrollback` (also :kbd:`⌘+F` on macOS)
Search scrollback in place :sc:`search_scrollback_prompt` ========================= =======================
========================== =======================
The in-place search highlights every match without replacing the screen with a
pager. It is bound to :kbd:`kitty_mod+alt+s` (:kbd:`Ctrl+Shift+Alt+S` by
default) and can also be run with :code:`kitten @ action
search_scrollback_prompt`. Prefix the query with ``\c`` to match case sensitively and with ``\r``
to use a regular expression; both modifiers can be combined. Write a doubled
backslash (``\\c``, ``\\r``) to search for those prefixes literally. While the search
is active, :kbd:`n` jumps to the next match, :kbd:`N` to the previous one and
:kbd:`Escape` ends it. The ``[current/total]`` counter is shown in the window
title, matches use the first mark color (see :opt:`mark1_foreground`) and the
current match uses the second one (:opt:`mark2_foreground`), so it stands out
from the other matches.
The :ac:`scrollback_search_next`, :ac:`scrollback_search_prev` and
:ac:`clear_scrollback_search` actions can also be mapped directly.
The scroll actions only take effect when the terminal is in the main screen. The scroll actions only take effect when the terminal is in the main screen.
When the alternate screen is active (for example when using a full screen When the alternate screen is active (for example when using a full screen
+2 -2
View File
@@ -2,7 +2,7 @@ Installer kitty
======================== ========================
Installation des binaires Installation des binaires
------------------------- ----------------
.. highlight:: sh .. highlight:: sh
@@ -143,7 +143,7 @@ dossier d'installation. Pour désinstaller, il suffit de supprimer ce dossier.
Compiler depuis les sources Compiler depuis les sources
--------------------------- ------------------------
|kitty| est facile à compiler depuis les sources, suivez les :doc:`instructions |kitty| est facile à compiler depuis les sources, suivez les :doc:`instructions
<build>`. <build>`.
+2 -2
View File
@@ -146,7 +146,7 @@ Dépendances de compilation :
Compiler et exécuter depuis les sources avec Nix Compiler et exécuter depuis les sources avec Nix
------------------------------------------------ -------------------------------------------
Sous NixOS ou tout autre système Linux ou macOS disposant du gestionnaire de Sous NixOS ou tout autre système Linux ou macOS disposant du gestionnaire de
paquets Nix, exécutez `nix-shell paquets Nix, exécutez `nix-shell
@@ -163,7 +163,7 @@ votre plateforme ci-dessus.
.. _packagers: .. _packagers:
Notes pour les empaqueteurs Linux/macOS Notes pour les empaqueteurs Linux/macOS
--------------------------------------- ----------------------------------
Le code source publié de |kitty| est disponible sous forme de `tarball`_ depuis Le code source publié de |kitty| est disponible sous forme de `tarball`_ depuis
`la page des versions GitHub `la page des versions GitHub
-143
View File
@@ -219,78 +219,6 @@ you use a decent Wayland compositor.
Detailed list of changes Detailed list of changes
------------------------------------- -------------------------------------
Fork FWS releases
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The versions below are the releases of the FWS fork, which carries its own
version so that a packaged build can be told apart from the upstream kitty it
is based on. Each entry names the issue it closed.
0.1.17 [2026-12-03]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
- The changelog now names each fork release with the issue it closed, instead
of leaving the fork changes in the accumulated upstream section. No
functional change.
0.1.16 [2026-12-03]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
- The clipboard history picker now shows when each entry was copied and the
title of the window the text will be pasted into, and :kbd:`↑`/:kbd:`↓` move
the highlighted entry so that :kbd:`Enter` pastes it without typing the
letters of a hint.
- The clicks of the docks are covered by tests: a left dock and a right dock
must both receive the clicks in their own area, and the layout tests pin the
position of a right dock instead of only its width.
0.1.15 [2026-12-03]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
- The :doc:`file manager <kittens/file-manager>` can be browsed with the mouse:
the wheel scrolls the list, a double click opens the entry under the pointer
like :kbd:`Enter`, and a right click opens the action palette on the clicked
row.
0.1.14 [2026-12-03]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
- :kbd:`Ctrl+Shift+H` browses the scrollback in a pager again with
:ac:`show_scrollback`: the keyboard shortcuts panel, which silently took the
key over while the documentation still promised the pager, moved to
:kbd:`Ctrl+Shift+Alt+H`.
0.1.13 [2026-12-03]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
- The in-place scrollback search got a usable default shortcut,
:kbd:`kitty_mod+alt+s`. It was bound to the same physical key as
:ac:`move_window_forward`, which allows the shifted fallback, so the last
definition won and the search never opened.
0.1.12 [2026-12-03]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
- The keyboard shortcuts panel keeps a long action name inside its own column,
shrinks its key column on very narrow docks so that a row always fits, and
shows the full name of the selected action on the help line, instead of
letting the edge of the dock cut the text.
0.1.11 [2026-12-03]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
- The current match of the in-place scrollback search is drawn with the second
mark color, so the match reached with :kbd:`n` and :kbd:`N` stands out from
the other ones without reading the window title.
0.1.10 [2026-12-03]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
- A literal :code:`\c` or :code:`\r` can be searched for by writing a doubled
backslash (:code:`\\c`, :code:`\\r`), instead of the query modifiers always
taking the prefix.
0.50.1 [unreleased] 0.50.1 [unreleased]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -304,89 +232,18 @@ is based on. Each entry names the issue it closed.
that ends a command without reporting a status (:code:`OSC 133;D` with no that ends a command without reporting a status (:code:`OSC 133;D` with no
argument) now shows :code:`0` instead of an empty status. argument) now shows :code:`0` instead of an empty status.
- kitty now keeps an in-memory history of the text copied to the clipboard,
which :ac:`paste_from_clipboard_history` and :ac:`search_clipboard_history`
can paste back. Nothing is written to disk and private clipboard writes are
never recorded. See :ref:`clipboard_history` for details. The picker shows
when each entry was copied and the title of the window the text will be
pasted into, and :kbd:`↑`/:kbd:`↓` select an entry so that :kbd:`Enter`
pastes it without typing the letters of a hint.
- kitty now remembers the state of the session that was in use when it exited,
in :file:`$XDG_STATE_HOME/kitty/last-session.json`, so that
:code:`kitty --session=last` brings back the tabs, layouts, working
directories and titles of the previous run. Restoring is explicit, never
automatic, and a corrupt or oversized saved state is discarded instead of
blocking startup. See :ref:`sessions` for details.
- The :doc:`file manager <kittens/file-manager>` now keeps its directory in
step with the shell by default: a :code:`cd` moves the panel into the same
directory and walking through the panel moves the shell at its next prompt,
for bash, zsh and fish. Nothing is typed into the terminal, so no command
lands in the history and a multi-line command being typed is left untouched.
Set :code:`sync_cwd no` in :file:`file-manager.conf` to keep the two
directories independent, as before.
- :kbd:`Ctrl+Shift+E` now opens the :doc:`file manager kitten - :kbd:`Ctrl+Shift+E` now opens the :doc:`file manager kitten
<kittens/file-manager>` in a left dock by default, instead of requiring a <kittens/file-manager>` in a left dock by default, instead of requiring a
manual mapping. This takes the key over from :ac:`open_url`; remap manual mapping. This takes the key over from :ac:`open_url`; remap
:kbd:`Ctrl+Shift+E` to :code:`open_url_with_hints` in :file:`kitty.conf` to :kbd:`Ctrl+Shift+E` to :code:`open_url_with_hints` in :file:`kitty.conf` to
restore the previous behavior. restore the previous behavior.
- The kitty shell now opens a searchable, categorized keyboard shortcut panel
in a side dock when :code:`help` is run without arguments, or when
:kbd:`kitty_mod+H` is pressed. The panel can also be started with
:code:`kitty +kitten help`.
- The :doc:`file manager <kittens/file-manager>` can now be browsed with the
mouse: the wheel scrolls the list, a double click opens the entry under the
pointer like :kbd:`Enter` and a right click opens the action palette on the
clicked row.
- The in-place scrollback search got a usable default shortcut: it was bound
to :kbd:`kitty_mod+shift+f`, the same physical key as :ac:`move_window_forward`
(which allows the shifted fallback), so the last definition won and the search
never opened. It is now on :kbd:`kitty_mod+alt+s`.
- The keyboard shortcuts panel moved from :kbd:`kitty_mod+h` to
:kbd:`kitty_mod+alt+h`, so that :kbd:`Ctrl+Shift+H` browses the scrollback in
a pager again with :ac:`show_scrollback`, as documented. The two actions
shared the same default trigger and the panel silently took the key over.
- The keyboard shortcuts panel ellipsizes a long action name inside its own
column instead of letting the edge of the dock cut it, shrinks its key column
on very narrow docks so that a row always fits, and shows the full name of
the selected action on the help line.
- The default :opt:`tab_title_template` now shows the abbreviated working
directory of the tab before its title, so the directory indicator of the tab
bar is visible without configuration.
- Accessibility: :kbd:`Tab` and :kbd:`Shift+Tab` move the selection in the - Accessibility: :kbd:`Tab` and :kbd:`Shift+Tab` move the selection in the
:doc:`file manager <kittens/file-manager>` and the :doc:`file manager <kittens/file-manager>` and the
:doc:`command palette <kittens/command-palette>` by default. A new :doc:`command palette <kittens/command-palette>` by default. A new
:doc:`accessibility guide </accessibility>` documents keyboard navigation and :doc:`accessibility guide </accessibility>` documents keyboard navigation and
the :opt:`text_fg_override_threshold` :code:`4.5 ratio` contrast mode. the :opt:`text_fg_override_threshold` :code:`4.5 ratio` contrast mode.
- The scrollback can now be searched in place: :ac:`search_scrollback_prompt`
highlights every match without opening the pager, shows the
:code:`[current/total]` counter in the window title and moves between matches
with :kbd:`n` and :kbd:`N`. Prefix the query with :code:`\c` for a case
sensitive search and :code:`\r` for a regular expression; write a doubled
backslash (:code:`\\c`, :code:`\\r`) to search for those prefixes literally.
The current match is drawn with the second mark color, so the match reached
with :kbd:`n` and :kbd:`N` is visible without looking at the window title.
See :doc:`basic` for the details.
- A configurable :opt:`leader` key now opens a which-key panel listing every
multi-key mapping available under that prefix, without waiting for a timeout.
The :doc:`command palette <kittens/command-palette>` shows the shortcut next
to each action and :kbd:`Ctrl+R` remaps it. See :ref:`leader_keymap`.
- The :doc:`file manager <kittens/file-manager>` now follows symbolic links to
directories, so they can be browsed like real ones, and expands a leading
:code:`~` in :code:`--start-dir`.
- A new :doc:`file manager kitten <kittens/file-manager>`, run with - A new :doc:`file manager kitten <kittens/file-manager>`, run with
:code:`kitten file-manager`, that browses directories in a side panel and :code:`kitten file-manager`, that browses directories in a side panel and
changes the working directory of the shell that launched it without leaving changes the working directory of the shell that launched it without leaving
-34
View File
@@ -264,37 +264,3 @@ to access the clipboard.
When the terminal sends an unsolicited paste event because the user triggered When the terminal sends an unsolicited paste event because the user triggered
a paste and the 5522 mode is enabled, there will be no associated id. In this a paste and the 5522 mode is enabled, there will be no associated id. In this
case, the multiplexer must forward the event to the currently active window. case, the multiplexer must forward the event to the currently active window.
.. _clipboard_history:
Clipboard history
---------------------
kitty keeps the last 50 pieces of plain text copied to the clipboard of each
instance, newest first, and lets you paste one of them back with
:ac:`paste_from_clipboard_history`. :ac:`search_clipboard_history` filters the
history with a fuzzy query before showing the list.
The picker lists the entries with the time each one was copied and names the
window that will receive the paste. Move the highlighted entry with :kbd:`↑` and
:kbd:`↓` and press :kbd:`Enter` to paste it, or type the letters of the hint
shown next to it. Press :kbd:`Escape` to cancel.
The history lives in memory only: it is never written to disk, so it disappears
when kitty exits and secrets copied during a session do not outlive it. Text
written by a program that marks its request as private (by passing a ``pw``
field in an *OSC 5522* write request) is never recorded, and neither is anything
copied to the primary selection. Images and other non-text data are ignored.
Both actions have a default shortcut: :kbd:`kitty_mod+alt+v` opens the
history and :kbd:`kitty_mod+alt+f` asks for a fuzzy query before showing the
list. To use different keys, add for example to :file:`kitty.conf`:
.. code-block:: conf
map kitty_mod+alt+h paste_from_clipboard_history
map kitty_mod+alt+g search_clipboard_history
The size of the history is fixed at 50 entries, 64 KiB per entry and 1 MiB in
total, so that a few large copies cannot use an unbounded amount of memory.
+6 -12
View File
@@ -20,7 +20,7 @@ from docutils import nodes
from docutils.parsers.rst.roles import normalize_options from docutils.parsers.rst.roles import normalize_options
from pygments.lexer import RegexLexer from pygments.lexer import RegexLexer
from pygments.lexer import bygroups as untyped_bygroups from pygments.lexer import bygroups as untyped_bygroups
from pygments.token import Comment, Error, Keyword, Literal, Name, Number, Punctuation, String, Whitespace from pygments.token import Comment, Error, Keyword, Literal, Name, Number, String, Whitespace
from sphinx import addnodes, version_info from sphinx import addnodes, version_info
from sphinx.util.logging import getLogger from sphinx.util.logging import getLogger
@@ -220,19 +220,15 @@ def commit_role(
name: str, rawtext: str, text: str, lineno: int, inliner: Any, options: Any = {}, content: Any = [] name: str, rawtext: str, text: str, lineno: int, inliner: Any, options: Any = {}, content: Any = []
) -> Tuple[List[nodes.reference], List[nodes.problematic]]: ) -> Tuple[List[nodes.reference], List[nodes.problematic]]:
"Link to a github commit" "Link to a github commit"
# The changelog also cites upstream kitty commits, which a shallow clone of
# the fork does not contain: link to the id as written instead of failing
# the documentation build over missing local history.
try: try:
commit_id = subprocess.check_output(f'git rev-list --max-count=1 {text}'.split(), stderr=subprocess.DEVNULL).decode('utf-8').strip() commit_id = subprocess.check_output(f'git rev-list --max-count=1 {text}'.split()).decode('utf-8').strip()
except Exception: except Exception:
commit_id = text msg = inliner.reporter.error(f'git commit id "{text}" not recognized.', line=lineno)
prb = inliner.problematic(rawtext, rawtext, msg)
return [prb], [msg]
url = f'https://github.com/kovidgoyal/kitty/commit/{commit_id}' url = f'https://github.com/kovidgoyal/kitty/commit/{commit_id}'
options = normalize_options(options) options = normalize_options(options)
try: short_id = subprocess.check_output(f'git rev-list --max-count=1 --abbrev-commit {commit_id}'.split()).decode('utf-8').strip()
short_id = subprocess.check_output(f'git rev-list --max-count=1 --abbrev-commit {commit_id}'.split(), stderr=subprocess.DEVNULL).decode('utf-8').strip()
except Exception:
short_id = commit_id
node = nodes.reference(rawtext, f'commit: {short_id}', refuri=url, **options) node = nodes.reference(rawtext, f'commit: {short_id}', refuri=url, **options)
return [node], [] return [node], []
@@ -511,8 +507,6 @@ class ConfLexer(RegexLexer):
tokens = { tokens = {
'root': [ 'root': [
(r'#.*?$', Comment.Single), (r'#.*?$', Comment.Single),
# Closing brace of a profile block, see :ref:`config-profiles`.
(r'\}', Punctuation),
(r'\s+$', Whitespace), (r'\s+$', Whitespace),
(r'\s+', Whitespace), (r'\s+', Whitespace),
(r'(include)(\s+)(.+?)$', bygroups(Comment.Preproc, Whitespace, Name.Namespace)), (r'(include)(\s+)(.+?)$', bygroups(Comment.Preproc, Whitespace, Name.Namespace)),
+2 -6
View File
@@ -100,16 +100,12 @@ quand même avec le reste de la configuration.
Les profils ne peuvent pas être imbriqués. Ils peuvent toutefois utiliser Les profils ne peuvent pas être imbriqués. Ils peuvent toutefois utiliser
:code:`include` et les autres directives d'inclusion. :code:`include` et les autres directives d'inclusion.
.. envvar:: KITTY_PROFILE
Nom du profil à activer au démarrage, voir :ref:`config-profiles`.
.. include:: /generated/conf-kitty.rst .. include:: /generated/conf-kitty.rst
Exemple de kitty.conf Exemple de kitty.conf
--------------------- --------------------
.. only:: html .. only:: html
@@ -133,7 +129,7 @@ Cela affichera le fichier de configuration par défaut commenté sur
:file:`STDOUT`. :file:`STDOUT`.
Toutes les actions associables Toutes les actions associables
------------------------------ ------------------------
Voir la :doc:`liste de tout ce que vous pouvez faire faire à |kitty| </actions>`. Voir la :doc:`liste de tout ce que vous pouvez faire faire à |kitty| </actions>`.
+4 -17
View File
@@ -83,10 +83,10 @@ Glossaire
.. _env_vars: .. _env_vars:
Variables d'environnement Variables d'environnement
------------------------- ------------------------
Variables qui influencent le comportement de kitty Variables qui influencent le comportement de kitty
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. envvar:: KITTY_CONFIG_DIRECTORY .. envvar:: KITTY_CONFIG_DIRECTORY
@@ -167,7 +167,7 @@ Variables qui influencent le comportement de kitty
Variables que kitty définit en lançant des programmes enfants Variables que kitty définit en lançant des programmes enfants
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. envvar:: LANG .. envvar:: LANG
@@ -181,24 +181,11 @@ Variables que kitty définit en lançant des programmes enfants
fonctions appelant :program:`kitty` fonctionnent correctement. fonctions appelant :program:`kitty` fonctionnent correctement.
.. envvar:: KITTY_WINDOW_ID .. envvar:: KITTY_WINDOW_ID
Un entier qui est l'identifiant de la :term:`fenêtre <window>` kitty dans Un entier qui est l'identifiant de la :term:`fenêtre <window>` kitty dans
laquelle le programme s'exécute. Utilisable avec la :doc:`facilité de laquelle le programme s'exécute. Utilisable avec la :doc:`facilité de
contrôle à distance de kitty <remote-control>`. contrôle à distance de kitty <remote-control>`.
.. envvar:: KITTY_CWD_SYNC_DIR
Le répertoire de session dans lequel les shells et les kittens qui coopèrent
échangent leur répertoire courant, voir la :ref:`synchronisation du
gestionnaire de fichiers <file_manager>`. Il n'est lisible que par votre
utilisateur et disparaît à la fin de la session.
.. envvar:: KITTY_SPECIAL_WINDOW_PARENT
Un entier qui est l'identifiant de la :term:`fenêtre <window>` pour laquelle
une fenêtre spéciale (overlay ou dock) a été ouverte. Absent des fenêtres
normales ; le :doc:`gestionnaire de fichiers </kittens/file-manager>` s'en
sert pour retrouver le shell dont il suit le répertoire.
.. envvar:: KITTY_PID .. envvar:: KITTY_PID
Un entier qui est l'identifiant du processus kitty dans lequel le programme Un entier qui est l'identifiant du processus kitty dans lequel le programme
+1 -1
View File
@@ -1,7 +1,7 @@
:orphan: :orphan:
L'interface en ligne de commande de kitty L'interface en ligne de commande de kitty
========================================= ====================================
.. program:: kitty .. program:: kitty
-26
View File
@@ -102,38 +102,12 @@ The following keys are available while the command palette is open:
- Jump to the last result - Jump to the last result
* - :kbd:`Backspace` * - :kbd:`Backspace`
- Delete the last character from the query - Delete the last character from the query
* - :kbd:`Ctrl+R`
- Remap the selected action by pressing its new shortcut
* - :kbd:`F12` * - :kbd:`F12`
- Toggle display of unmapped actions - Toggle display of unmapped actions
* - Mouse click * - Mouse click
- Select and run the clicked action - Select and run the clicked action
Remapping a shortcut
----------------------
Each row shows the shortcut bound to the action in its key column. Select an
action and press :kbd:`Ctrl+R`, then press the new shortcut. The palette appends
the corresponding :code:`map` directive to :file:`kitty.conf` and reloads the
configuration, so the change takes effect immediately without restarting
|kitty|. Existing lines are left untouched and the new mapping is appended, so
the most recent mapping wins. The read-only shortcuts panel does not offer
remapping, and mouse bindings cannot be remapped this way.
Leader key tree
-----------------
When the :opt:`leader` option is set and a multi-key mapping starts with the
leader key, pressing it opens the palette in which-key mode. Only the
continuations available under the leader prefix are listed, with their help
text. Press the key shown in the key column to run that action immediately, or
use the arrow keys and :kbd:`Enter`. This mode does not remap or run unmapped
actions, it is purely a keyboard tree. See :ref:`leader_keymap` for the
configuration example.
Unmapped actions Unmapped actions
------------------ ------------------
+4 -64
View File
@@ -27,8 +27,7 @@ Il peut aussi tourner dans un :doc:`panneau du bureau </kittens/panel>` ou dans
n'importe quelle :term:`fenêtre kitty <window>` classique. n'importe quelle :term:`fenêtre kitty <window>` classique.
Le répertoire de départ est celui de la fenêtre courante, sauf si un répertoire Le répertoire de départ est celui de la fenêtre courante, sauf si un répertoire
est passé en argument ou avec ``--start-dir``. Un chemin commençant par ``~`` est passé en argument ou avec ``--start-dir``.
y est développé, même lorsqu'il vient d'un mappage où le shell ne l'a pas fait.
.. note:: .. note::
@@ -36,8 +35,7 @@ y est développé, même lorsqu'il vient d'un mappage où le shell ne l'a pas fa
panneau a été lancé. Lancé dans un dock ou un panneau du bureau, il ne change panneau a été lancé. Lancé dans un dock ou un panneau du bureau, il ne change
donc pas le répertoire du shell : :kbd:`Ctrl+Entrée` ferme le panneau sans donc pas le répertoire du shell : :kbd:`Ctrl+Entrée` ferme le panneau sans
déplacer le shell. Lancez le panneau depuis une fenêtre de shell pour changer déplacer le shell. Lancez le panneau depuis une fenêtre de shell pour changer
de répertoire, sauf si la synchronisation décrite plus bas est activée : le de répertoire.
dock suit alors la fenêtre active du groupe au moment de sa création.
L'ouverture d'un fichier, elle, fonctionne partout : le panneau confie le L'ouverture d'un fichier, elle, fonctionne partout : le panneau confie le
fichier à kitty, qui lance l'éditeur dans un nouvel onglet. Le fichier fichier à kitty, qui lance l'éditeur dans un nouvel onglet. Le fichier
@@ -61,10 +59,7 @@ Actions
utilisez :code:`sudo -e` depuis le shell. utilisez :code:`sudo -e` depuis le shell.
:kbd:`→` ou :kbd:`L` :kbd:`→` ou :kbd:`L`
descend dans le répertoire sélectionné ; le shell y va aussi, au prompt descend dans le répertoire sélectionné sans toucher au shell.
suivant, quand la synchronisation est active. Un lien symbolique vers un
répertoire se parcourt comme un répertoire ; un lien cassé reste une entrée
ordinaire, ouverte dans l'éditeur.
:kbd:`←`, :kbd:`Retour arrière` ou :kbd:`H` :kbd:`←`, :kbd:`Retour arrière` ou :kbd:`H`
remonte au répertoire parent. remonte au répertoire parent.
@@ -116,59 +111,7 @@ Actions
affiche ou masque les entrées cachées. affiche ou masque les entrées cachées.
:kbd:`Échap` ou :kbd:`Q` :kbd:`Échap` ou :kbd:`Q`
ferme le panneau sans rien changer : une demande de synchronisation que le ferme le panneau sans rien changer.
shell n'a pas encore lue est retirée, il reste donc où il était.
Synchronisation avec le shell
------------------------------
Le panneau et le shell partagent leur répertoire courant depuis la version
0.50.1, dans les deux sens : un :code:`cd` dans le shell amène le panneau dans
le même répertoire, et chaque répertoire ouvert dans le panneau devient aussi
celui du shell, sans même avoir à valider. Pour que chacun garde son propre
répertoire, alors que le panneau part toujours de celui du shell et n'en change
plus ::
# ~/.config/kitty/file-manager.conf
sync_cwd no
L'échange ne passe pas par le terminal. kitty exporte un répertoire de session
dans :envvar:`KITTY_CWD_SYNC_DIR` ; le shell y publie son répertoire courant et
le panneau y dépose celui qu'il veut. Le panneau retrouve le shell qui l'a lancé
grâce à :envvar:`KITTY_SPECIAL_WINDOW_PARENT`. L'intégration shell de kitty, pour
bash, zsh et fish, applique la demande avec :code:`builtin cd` : aucune commande
n'entre dans l'historique et une commande multi-lignes en cours de saisie n'est
pas soumise.
.. note::
La synchronisation demande l'intégration shell de kitty, active par défaut
pour bash, zsh et fish. Les autres shells gardent le comportement précédent :
le panneau retape la commande :code:`cd` dans le terminal, comme lorsque
l'option est désactivée.
Le changement est appliqué au prompt suivant : le shell se déplace quand la
commande suivante démarre, ou qu'une ligne vide est validée, et non pendant
que vous parcourez le panneau. C'est le prix à payer pour ne jamais écrire
dans le terminal. Si vous quittez le panneau avec :kbd:`Échap` avant que le
shell ait lu la demande, elle est retirée et le shell ne bouge pas.
Lancé dans un dock, le panneau suit la fenêtre active du groupe au moment où
le dock est créé. Si vous passez ensuite à une autre fenêtre du même groupe,
il continue de suivre cette première fenêtre : relancez le dock pour changer
de cible. Dans un panneau du bureau, il n'y a pas de shell à suivre et la
synchronisation reste inerte.
Souris
------
Le panneau se pilote aussi à la souris. La molette parcourt la liste par pas de
trois lignes, sans transmettre l'événement au terminal qui héberge le dock. Un
double-clic ouvre l'entrée sous le pointeur, comme :kbd:`Entrée` : un répertoire
est parcouru, un fichier est confié à l'éditeur. Un clic droit ouvre la palette
d'actions sur la ligne cliquée, identique au raccourci :kbd:`:`.
.. _file-manager-shortcuts: .. _file-manager-shortcuts:
@@ -245,9 +188,6 @@ Limites
pour changer de répertoire ; utilisez-le depuis une fenêtre de shell. pour changer de répertoire ; utilisez-le depuis une fenêtre de shell.
- Le panneau ne suit pas les modifications faites par d'autres programmes : - Le panneau ne suit pas les modifications faites par d'autres programmes :
utilisez :kbd:`Ctrl+R` pour relire le répertoire. utilisez :kbd:`Ctrl+R` pour relire le répertoire.
- Les liens symboliques ne sont pas distingués des fichiers ordinaires dans
l'affichage : seul le fait qu'ils pointent vers un répertoire change leur
comportement à l'ouverture.
.. include:: /generated/conf-kitten-file_manager.rst .. include:: /generated/conf-kitten-file_manager.rst
-55
View File
@@ -1,55 +0,0 @@
Panneau d'aide aux raccourcis
=============================
.. program:: kitty +kitten help
Le panneau d'aide affiche tous les raccourcis clavier actifs, triés par
catégorie, avec une recherche rapide. Il s'ouvre dans un dock latéral, comme le
gestionnaire de fichiers, et reste en lecture seule : :kbd:`Entrée` ne déclenche
aucune action. Il est mappé sur :kbd:`kitty_mod+alt+h`
(:kbd:`Ctrl+Shift+Alt+H` par défaut), pour laisser :kbd:`kitty_mod+h` à
:ac:`show_scrollback`.
Utilisation
-----------
Dans le :doc:`shell kitty </remote-control>` (:kbd:`Ctrl+Shift+Échap`), la commande
``help`` sans argument ouvre le panneau, tout comme :kbd:`kitty_mod+alt+h` dans
n'importe quelle fenêtre ::
help
Depuis un terminal, lancez le kitten directement ::
kitty +kitten help
Pour l'ouvrir dans un dock depuis un raccourci de ``kitty.conf`` ::
map kitty_mod+f4 launch --type=window-dock --dock-edge=left --dock-size=60 kitty +kitten help
Commandes
---------
.. table::
===================== ===================================================
Touche Action
===================== ===================================================
Texte Filtre les raccourcis (recherche floue).
:kbd:`Entrée` Sans effet : le panneau est une référence.
:kbd:`Échap` Efface la requête, puis ferme le panneau.
:kbd:`↑`, :kbd:`↓` Sélectionne le raccourci précédent ou suivant.
:kbd:`Tab` Sélectionne le raccourci suivant.
:kbd:`Shift+Tab` Sélectionne le raccourci précédent.
:kbd:`Ctrl+K` Sélectionne le raccourci précédent.
:kbd:`Ctrl+J` Sélectionne le raccourci suivant.
:kbd:`Page↑` Défile d'une page vers le haut.
:kbd:`Page↓` Défile d'une page vers le bas.
:kbd:`Début` Premier raccourci.
:kbd:`Fin` Dernier raccourci.
:kbd:`F12` Affiche ou masque les actions sans raccourci.
===================== ===================================================
Les raccourcis affichés proviennent de la configuration effective de kitty :
les remappages de ``kitty.conf`` sont donc visibles. Les actions sans raccourci
sont masquées par défaut ; :kbd:`F12` les affiche.
+1 -7
View File
@@ -1,7 +1,7 @@
.. _kittens: .. _kittens:
Étendre avec les kittens Étendre avec les kittens
------------------------ -----------------------
.. toctree:: .. toctree::
:hidden: :hidden:
@@ -14,7 +14,6 @@
kittens/choose-fonts kittens/choose-fonts
kittens/hints kittens/hints
kittens/command-palette kittens/command-palette
kittens/help
kittens/quick-access-terminal kittens/quick-access-terminal
kittens/choose-files kittens/choose-files
kittens/dnd kittens/dnd
@@ -67,11 +66,6 @@ et à créer des programmes autonomes utiles. Quelques kittens importants :
depuis une seule surcouche de recherche. depuis une seule surcouche de recherche.
:doc:`Aide aux raccourcis <kittens/help>`
Consultez tous les raccourcis clavier dans un panneau latéral, avec une
recherche rapide et un classement par catégorie.
:doc:`Terminal à accès rapide <kittens/quick-access-terminal>` :doc:`Terminal à accès rapide <kittens/quick-access-terminal>`
Accédez à une fenêtre kitty flottante et semi-transparente d'accès rapide Accédez à une fenêtre kitty flottante et semi-transparente d'accès rapide
avec une seule combinaison de touches. avec une seule combinaison de touches.
+3 -3
View File
@@ -124,7 +124,7 @@ Par exemple ::
.. _watchers: .. _watchers:
Surveiller les fenêtres lancées Surveiller les fenêtres lancées
------------------------------- ---------------------------
L'option :option:`launch --watcher` vous permet d'indiquer des fonctions Python L'option :option:`launch --watcher` vous permet d'indiquer des fonctions Python
qui seront appelées lors d'événements précis, comme le redimensionnement ou la qui seront appelées lors d'événements précis, comme le redimensionnement ou la
@@ -238,7 +238,7 @@ de contrôle à distance à votre disposition.
Recherche des exécutables Recherche des exécutables
------------------------- -----------------------
Lorsque vous indiquez une commande à exécuter sous forme de simple nom plutôt Lorsque vous indiquez une commande à exécuter sous forme de simple nom plutôt
que de chemin absolu, elle est recherchée dans la variable d'environnement que de chemin absolu, elle est recherchée dans la variable d'environnement
@@ -252,6 +252,6 @@ shell est utilisée.
Voir :opt:`exe_search_path` pour les détails et la façon de contrôler cela. Voir :opt:`exe_search_path` pour les détails et la façon de contrôler cela.
Référence de syntaxe Référence de syntaxe
-------------------- ------------------
.. include:: /generated/launch.rst .. include:: /generated/launch.rst
-50
View File
@@ -428,61 +428,11 @@ below::
map --new-mode XXX --on-action end ... map --new-mode XXX --on-action end ...
.. _leader_keymap:
Leader key and which-key hints
-----------------------------------
The leader key turns a group of multi-key mappings into a discoverable tree.
Set :opt:`leader` to the prefix you want to use, then define mappings that
start with that prefix::
leader ctrl+space
map ctrl+space>n new_os_window
map ctrl+space>w new_window
map ctrl+space>t new_tab
map ctrl+space>c close_window
Pressing :kbd:`Ctrl+Space` immediately opens a panel listing every key that can
follow, with the action it runs and its help text. Press the key shown in the
first column to run the action directly, or use the arrow keys and
:kbd:`Enter`/ :kbd:`Escape` to leave. No timeout is needed: the panel opens as
soon as the leader key is pressed.
The panel reads the same structured mapping data as the :doc:`command palette
</kittens/command-palette>` and :doc:`the shortcuts help panel
</kittens/help>`, so every action they list is also available here. Bindings
guarded by :code:`--when-focus-on` are filtered against the focused window
before they are shown.
The leader key is only intercepted when multi-key mappings actually start with
it. Otherwise it is passed to the program running in the window normally. Set
:opt:`leader` to :code:`none` to disable the panel.
All mappable actions All mappable actions
------------------------ ------------------------
There is a list of :doc:`all mappable actions <actions>`. There is a list of :doc:`all mappable actions <actions>`.
Remapping from the command palette
----------------------------------
Every entry in the command palette shows the shortcut currently bound to it.
Select an action and press :kbd:`Ctrl+R` to remap it: the footer asks for the
new shortcut, so press the key combination you want. The palette appends a
:code:`map` directive to :file:`kitty.conf` and reloads the configuration, so
the new shortcut is active immediately::
map ctrl+alt+n new_os_window
The change is appended to the end of the file, it never rewrites existing lines.
A later mapping for the same key wins, as usual in :file:`kitty.conf`. Remove
the line manually to undo the change. Remapping is disabled in the read-only
shortcuts help panel and for mouse bindings.
Debugging mapping issues Debugging mapping issues
------------------------------ ------------------------------
+4 -4
View File
@@ -1,5 +1,5 @@
Marquer du texte à l'écran Marquer du texte à l'écran
-------------------------- ---------------------
kitty peut marquer du texte à l'écran à partir d'expressions régulières. C'est kitty peut marquer du texte à l'écran à partir d'expressions régulières. C'est
@@ -67,7 +67,7 @@ Vous pouvez aussi utiliser les facilités de :doc:`contrôle à distance
Défiler jusqu'aux marques Défiler jusqu'aux marques
------------------------- --------------------
kitty dispose d'une action :ac:`scroll_to_mark` pour défiler jusqu'à la ligne kitty dispose d'une action :ac:`scroll_to_mark` pour défiler jusqu'à la ligne
suivante contenant une marque. Vous pouvez l'utiliser en l'associant à un suivante contenant une marque. Vous pouvez l'utiliser en l'associant à un
@@ -88,7 +88,7 @@ Ce qui ne défilera que vers les marques de type 1.
La syntaxe complète pour créer des marques La syntaxe complète pour créer des marques
------------------------------------------ -------------------------------------
La syntaxe de l'action :ac:`toggle_marker` est :: La syntaxe de l'action :ac:`toggle_marker` est ::
@@ -105,7 +105,7 @@ Ici :code:`marker-type` vaut l'un des suivants :
.. _marker_funcs: .. _marker_funcs:
Fonctions de marqueur arbitraires Fonctions de marqueur arbitraires
--------------------------------- -----------------------------
Vous pouvez créer vos propres fonctions de marqueur. Créez un fichier Python Vous pouvez créer vos propres fonctions de marqueur. Créez un fichier Python
nommé :file:`mymarker.py` et, à l'intérieur, une fonction :code:`marker`. Cette nommé :file:`mymarker.py` et, à l'intérieur, une fonction :code:`marker`. Cette
+1 -1
View File
@@ -90,7 +90,7 @@ ci-dessous :
.. _matching_criteria: .. _matching_criteria:
Critères de correspondance Critères de correspondance
-------------------------- ------------------
Une entrée de :file:`open-actions.conf` doit avoir un ou plusieurs critères de Une entrée de :file:`open-actions.conf` doit avoir un ou plusieurs critères de
correspondance. Les URL qui satisfont tous les critères d'une entrée déclenchent correspondance. Les URL qui satisfont tous les critères d'une entrée déclenchent
+10 -11
View File
@@ -52,7 +52,7 @@ les détails.
.. _layouts: .. _layouts:
Dispositions Dispositions
------------ ----------
Une :term:`disposition <layout>` est un agencement de plusieurs Une :term:`disposition <layout>` est un agencement de plusieurs
:term:`fenêtres kitty <window>` à l'intérieur d'une :term:`fenêtre OS :term:`fenêtres kitty <window>` à l'intérieur d'une :term:`fenêtre OS
@@ -130,7 +130,7 @@ sur le contrôle à distance.
Contrôle à distance Contrôle à distance
------------------- ------------------
|kitty| dispose d'un système très puissant qui vous permet de le piloter |kitty| dispose d'un système très puissant qui vous permet de le piloter
depuis :doc:`l'invite du shell, même via SSH <remote-control>`. Vous pouvez depuis :doc:`l'invite du shell, même via SSH <remote-control>`. Vous pouvez
@@ -159,7 +159,7 @@ facilement d'une session à l'autre avec une combinaison de touches. Voir
Créer des onglets et des fenêtres Créer des onglets et des fenêtres
--------------------------------- -------------------------------
kitty peut exécuter des programmes arbitraires dans de nouveaux :term:`onglets kitty peut exécuter des programmes arbitraires dans de nouveaux :term:`onglets
<tab>`, :term:`fenêtres <window>` ou :term:`surcouches <overlay>` sur une <tab>`, :term:`fenêtres <window>` ou :term:`surcouches <overlay>` sur une
@@ -172,7 +172,7 @@ combinaison de touches. Pour apprendre comment faire, voir :doc:`ici <launch>`.
Fonctionnalités de la souris Fonctionnalités de la souris
---------------------------- -------------------
* Vous pouvez cliquer sur une URL pour l'ouvrir dans un navigateur. * Vous pouvez cliquer sur une URL pour l'ouvrir dans un navigateur.
* Vous pouvez double-cliquer pour sélectionner un mot, puis glisser pour * Vous pouvez double-cliquer pour sélectionner un mot, puis glisser pour
@@ -233,7 +233,7 @@ de nouveaux onglets, ou double-cliquer sur un onglet existant pour le renommer.
open_actions open_actions
Contrôle des polices Contrôle des polices
-------------------- -----------------
|kitty| dispose de fonctionnalités de sélection de polices extrêmement |kitty| dispose de fonctionnalités de sélection de polices extrêmement
souples et puissantes. Vous pouvez indiquer des familles individuelles pour souples et puissantes. Vous pouvez indiquer des familles individuelles pour
@@ -252,7 +252,7 @@ Le tampon d'historique
|kitty| prend en charge le défilement arrière pour consulter l'historique, |kitty| prend en charge le défilement arrière pour consulter l'historique,
comme la plupart des terminaux. Vous pouvez utiliser les raccourcis clavier ou comme la plupart des terminaux. Vous pouvez utiliser les raccourcis clavier ou
la molette de la souris. |kitty| affiche une :opt:`scrollbar` la molette de la souris. |kitty| affiche une :opt:`barre de défilement`
interactive le long du bord droit de la fenêtre, qui montre votre position interactive le long du bord droit de la fenêtre, qui montre votre position
actuelle dans l'historique. Vous pouvez cliquer et faire glisser la barre de actuelle dans l'historique. Vous pouvez cliquer et faire glisser la barre de
défilement pour naviguer rapidement dans l'historique. défilement pour naviguer rapidement dans l'historique.
@@ -267,13 +267,12 @@ formatage du texte sont préservés. Vous pouvez explorer confortablement le
tampon d'historique dans le pager. tampon d'historique dans le pager.
De plus, vous pouvez envoyer le contenu du tampon d'historique à une commande De plus, vous pouvez envoyer le contenu du tampon d'historique à une commande
arbitraire exécutée dans une nouvelle :term:`fenêtre <window>`, un nouvel arbitraire exécutée dans une nouvelle :term:`fenêtre`, un nouvel :term:`onglet`
:term:`onglet <tab>` ou une :term:`surcouche <overlay>`. Par exemple :: ou une :term:`surcouche`. Par exemple ::
map f1 launch --stdin-source=@screen_scrollback --stdin-add-formatting less +G -R map f1 launch --stdin-source=@screen_scrollback --stdin-add-formatting less +G -R
ouvrira le tampon d'historique dans une nouvelle :term:`fenêtre <window>` lorsque ouvrira le tampon d'historique dans une nouvelle :term:`fenêtre` lorsque vous
vous
appuyez sur la touche :kbd:`F1`. Voir :sc:`show_scrollback <show_scrollback>` appuyez sur la touche :kbd:`F1`. Voir :sc:`show_scrollback <show_scrollback>`
pour les détails. pour les détails.
@@ -308,7 +307,7 @@ les détails.
.. _cpbuf: .. _cpbuf:
Plusieurs tampons de copier/coller Plusieurs tampons de copier/coller
---------------------------------- -----------------------------
En plus du copier/coller depuis le presse-papiers du système, vous pouvez En plus du copier/coller depuis le presse-papiers du système, vous pouvez
configurer dans |kitty| un nombre arbitraire de tampons de copier/coller. Pour configurer dans |kitty| un nombre arbitraire de tampons de copier/coller. Pour
+2 -2
View File
@@ -30,7 +30,7 @@ d'énergie pour les tâches courantes, la latence entre le clavier et l'écran,
le débit (traitement de grandes quantités de données). le débit (traitement de grandes quantités de données).
Latence entre le clavier et l'écran Latence entre le clavier et l'écran
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Elle se mesure soit avec du matériel dédié, soit avec des logiciels comme Elle se mesure soit avec du matériel dédié, soit avec des logiciels comme
`Typometer <https://pavelfatin.com/typometer/>`__. Les mesures de tiers `Typometer <https://pavelfatin.com/typometer/>`__. Les mesures de tiers
@@ -122,7 +122,7 @@ d'échappement de formatage typiques et de texte uniquement ASCII.
Consommation d'énergie Consommation d'énergie
^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^
Malheureusement, je n'ai pas l'infrastructure pour mesurer la consommation Malheureusement, je n'ai pas l'infrastructure pour mesurer la consommation
d'énergie réelle, l'utilisation du processeur devra donc la représenter. Voici d'énergie réelle, l'utilisation du processeur devra donc la représenter. Voici
-24
View File
@@ -34,30 +34,6 @@ you want to work on the project, simply run:
You can also set the session in :file:`kitty.conf` via :opt:`startup_session`. You can also set the session in :file:`kitty.conf` via :opt:`startup_session`.
Restoring the last session
----------------------------
kitty saves the state of its tabs, windows, layouts, working directories and
titles when it exits, in :file:`$XDG_STATE_HOME/kitty/last-session.json`
(usually :file:`~/.local/state/kitty/last-session.json`). The saved state is
limited to 1 MiB and is overwritten at every exit, so it never accumulates.
To restore it, start kitty with:
.. code-block:: sh
kitty --session=last
The same saved state can be restored inside a running kitty with the
:ac:`restore_last_session` action, which is mapped to :kbd:`kitty_mod+alt+r`
by default and adds the saved tabs to the current window.
Restoring is never automatic: without this option the saved state is ignored,
so an unexpected state is never imposed on you. A state file that is corrupt,
unreadable or too large is discarded and kitty starts normally. :code:`cd`
directives whose directory no longer exists are dropped when restoring. Use
:ac:`save_as_session` for sessions that must survive beyond the next exit.
Thus, it is very easy to create sessions and work on projects. To learn how to Thus, it is very easy to create sessions and work on projects. To learn how to
create more complex sessions, see :ref:`complex_sessions`. create more complex sessions, see :ref:`complex_sessions`.
+1 -1
View File
@@ -1,5 +1,5 @@
Soutenez le développement de kitty ❤️ Soutenez le développement de kitty ❤️
===================================== ==============================
Mon objectif avec |kitty| est de faire avancer l'écosystème stagnant des Mon objectif avec |kitty| est de faire avancer l'écosystème stagnant des
terminaux. Dans cette optique, kitty possède de nombreuses fonctionnalités terminaux. Dans cette optique, kitty possède de nombreuses fonctionnalités
+36 -279
View File
@@ -38,15 +38,6 @@ type InputData struct {
Mouse []Binding `json:"mouse"` Mouse []Binding `json:"mouse"`
ModeOrder []string `json:"mode_order"` ModeOrder []string `json:"mode_order"`
CategoryOrder map[string][]string `json:"category_order"` CategoryOrder map[string][]string `json:"category_order"`
Leader *LeaderData `json:"leader"`
}
// LeaderData is the which-key tree shown when the configured leader key is
// pressed. Key holds the key to press after the leader, not the full shortcut.
type LeaderData struct {
Prefix string `json:"prefix"`
Title string `json:"title"`
Bindings []Binding `json:"bindings"`
} }
// wordToken represents a single word extracted from column text, with its // wordToken represents a single word extracted from column text, with its
@@ -220,57 +211,28 @@ type displayLine struct {
const maxKeyDisplayWidth = 30 const maxKeyDisplayWidth = 30
// keyWidthFor is the number of cells reserved for the key itself. On a very
// narrow panel it shrinks, so that the action column still has room and the row
// never extends past the edge of the panel.
func keyWidthFor(panelWidth int) int {
return min(maxKeyDisplayWidth, max(panelWidth-10, 1))
}
// keyColumnWidthFor is the number of cells the key column takes: the four space
// indent, the padded key and the separating space.
func keyColumnWidthFor(panelWidth int) int {
return 4 + keyWidthFor(panelWidth) + 1
}
// unmappedLabel is shown in the key column for actions with no keyboard shortcut. // unmappedLabel is shown in the key column for actions with no keyboard shortcut.
const unmappedLabel = "(unmapped)" const unmappedLabel = "(unmapped)"
// ellipsis marks a truncated string. It is a single cell, so that as much of the // truncateToWidth truncates s to fit within maxWidth cells, appending "..." if
// original text as possible is kept inside the panel. // truncated and maxWidth > 3. When maxWidth <= 3, the string is simply trimmed
const ellipsis = "…" // to fit without appending ellipsis (no room for it).
// truncateToWidth truncates s to fit within maxWidth cells, appending "…" if
// truncated and maxWidth > 1. When maxWidth <= 1, the string is simply trimmed
// to fit without appending the ellipsis (no room for it).
func truncateToWidth(s string, maxWidth int) string { func truncateToWidth(s string, maxWidth int) string {
if wcswidth.Stringwidth(s) <= maxWidth { if wcswidth.Stringwidth(s) <= maxWidth {
return s return s
} }
ellipsisWidth := wcswidth.Stringwidth(ellipsis)
runes := []rune(s) runes := []rune(s)
if maxWidth <= ellipsisWidth { if maxWidth <= 3 {
// Not enough room for the ellipsis; just trim to fit // Not enough room for ellipsis; just trim to fit
for len(runes) > 0 && wcswidth.Stringwidth(string(runes)) > maxWidth { for len(runes) > 0 && wcswidth.Stringwidth(string(runes)) > maxWidth {
runes = runes[:len(runes)-1] runes = runes[:len(runes)-1]
} }
return string(runes) return string(runes)
} }
for len(runes) > 0 && wcswidth.Stringwidth(string(runes))+ellipsisWidth > maxWidth { for len(runes) > 0 && wcswidth.Stringwidth(string(runes))+3 > maxWidth {
runes = runes[:len(runes)-1] runes = runes[:len(runes)-1]
} }
return string(runes) + ellipsis return string(runes) + "..."
}
// actionColumnWidth is the number of cells left for the action column of a row,
// so that a long action name is ellipsized inside the panel instead of being cut
// by its edge. The category suffix, only shown in search results, is reserved.
func (h *Handler) actionColumnWidth(width int, b *Binding) int {
used := keyColumnWidthFor(width)
if h.query != "" && h.leader == nil {
used += categorySuffixWidth(b)
}
return max(width-used, 1)
} }
// sectionHeader returns a separator line like " ── label ─────────". // sectionHeader returns a separator line like " ── label ─────────".
@@ -313,13 +275,6 @@ type Handler struct {
cv *utils.CachedValues[*CachedSettings] cv *utils.CachedValues[*CachedSettings]
shortcut_tracker config.ShortcutTracker shortcut_tracker config.ShortcutTracker
keyboard_shortcuts []*config.KeyAction keyboard_shortcuts []*config.KeyAction
read_only bool
data_file string
leader *LeaderData
remap_mode bool
remap_binding *Binding
remap_key string
remap_action string
} }
// initialize sets up the TUI: screen size, cursor, cached settings, and initial data load. // initialize sets up the TUI: screen size, cursor, cached settings, and initial data load.
@@ -332,39 +287,17 @@ func (h *Handler) initialize() (string, error) {
h.lp.SetCursorVisible(true) h.lp.SetCursorVisible(true)
h.lp.SetCursorShape(loop.BAR_CURSOR, true) h.lp.SetCursorShape(loop.BAR_CURSOR, true)
h.lp.AllowLineWrapping(false) h.lp.AllowLineWrapping(false)
title := "Command Palette" h.lp.SetWindowTitle("Command Palette")
if h.read_only {
title = "Keyboard shortcuts"
}
if h.input_data.Leader != nil {
title = h.input_data.Leader.Title
if title == "" {
title = "Leader keys"
}
}
h.lp.SetWindowTitle(title)
if h.read_only { // Initialize with ShowUnmapped: true as the default; Load() returns this
// A reference panel is about bindings, not about actions without one. // default when no cache file exists yet.
h.show_unmapped = false h.cv = utils.NewCachedValues("command-palette", &CachedSettings{ShowUnmapped: true})
} else if h.input_data.Leader != nil { settings := h.cv.Load()
// The leader panel lists exactly the keys that are available. h.show_unmapped = settings.ShowUnmapped
h.show_unmapped = true
} else {
// Initialize with ShowUnmapped: true as the default; Load() returns this
// default when no cache file exists yet.
h.cv = utils.NewCachedValues("command-palette", &CachedSettings{ShowUnmapped: true})
settings := h.cv.Load()
h.show_unmapped = settings.ShowUnmapped
}
h.keyboard_shortcuts = config.ResolveShortcuts(NewConfig().KeyboardShortcuts) h.keyboard_shortcuts = config.ResolveShortcuts(NewConfig().KeyboardShortcuts)
if h.data_file != "" { if err := h.loadData(); err != nil {
if err := h.loadDataFile(); err != nil {
return "", err
}
} else if err := h.loadData(); err != nil {
return "", err return "", err
} }
@@ -380,48 +313,17 @@ func (h *Handler) loadData() error {
if err != nil { if err != nil {
return fmt.Errorf("failed to read stdin: %w", err) return fmt.Errorf("failed to read stdin: %w", err)
} }
return h.parseData(data)
}
// loadDataFile reads the JSON produced by the help kitten and removes it so
// that repeated launches do not leave temporary files behind.
func (h *Handler) loadDataFile() error {
data, err := os.ReadFile(h.data_file)
if err != nil {
return fmt.Errorf("failed to read keybinding data: %w", err)
}
_ = os.Remove(h.data_file)
return h.parseData(data)
}
func (h *Handler) parseData(data []byte) error {
if len(data) == 0 { if len(data) == 0 {
return fmt.Errorf("no keybinding data received") return fmt.Errorf("no input data received on stdin; this kitten must be launched from kitty")
} }
if err := json.Unmarshal(data, &h.input_data); err != nil { if err := json.Unmarshal(data, &h.input_data); err != nil {
return fmt.Errorf("failed to parse input data: %w", err) return fmt.Errorf("failed to parse input data: %w", err)
} }
if h.input_data.Leader != nil {
h.leader = h.input_data.Leader
h.flattenLeaderBindings()
return nil
}
h.flattenBindings() h.flattenBindings()
return nil return nil
} }
// flattenLeaderBindings turns the leader tree produced by Python into display
// items. The key column already holds only the key to press after the leader.
func (h *Handler) flattenLeaderBindings() {
for _, b := range h.input_data.Leader.Bindings {
b.Category = "Leader"
b.Mode = ""
b.IsMouse = false
h.all_items = append(h.all_items, bindingToDisplayItem(b))
}
}
// bindingToDisplayItem converts a Binding into a DisplayItem with pre-tokenized // bindingToDisplayItem converts a Binding into a DisplayItem with pre-tokenized
// words for word-level matching. // words for word-level matching.
func bindingToDisplayItem(b Binding) DisplayItem { func bindingToDisplayItem(b Binding) DisplayItem {
@@ -663,30 +565,17 @@ func (h *Handler) draw_screen() {
h.lp.QueueWriteString(h.query) h.lp.QueueWriteString(h.query)
// Draw results // Draw results
if h.leader != nil { if h.query == "" {
h.drawFlatResults(resultsStartY, resultsHeight, width)
} else if h.query == "" {
h.drawGroupedResults(resultsStartY, resultsHeight, width) h.drawGroupedResults(resultsStartY, resultsHeight, width)
} else { } else {
h.drawFlatResults(resultsStartY, resultsHeight, width) h.drawFlatResults(resultsStartY, resultsHeight, width)
} }
// Draw help text for selected binding, falling back to the full action name // Draw help text for selected binding
// when the action column had to ellipsize it
h.lp.MoveCursorTo(1, helpY) h.lp.MoveCursorTo(1, helpY)
if b := h.selectedBinding(); b != nil { if b := h.selectedBinding(); b != nil && b.Help != "" {
detail := b.Help helpStr := truncateToWidth(b.Help, max(width-2, 3))
if full := h.selectedActionText(); wcswidth.Stringwidth(full) > h.actionColumnWidth(width, b) { h.lp.QueueWriteString(h.lp.SprintStyled("dim italic", " "+helpStr))
if detail == "" {
detail = full
} else {
detail = full + " " + detail
}
}
if detail != "" {
helpStr := truncateToWidth(detail, max(width-2, 1))
h.lp.QueueWriteString(h.lp.SprintStyled("dim italic", " "+helpStr))
}
} }
// Draw key hints footer // Draw key hints footer
@@ -695,25 +584,10 @@ func (h *Handler) draw_screen() {
if h.show_unmapped { if h.show_unmapped {
unmappedToggleLabel = "Hide" unmappedToggleLabel = "Hide"
} }
footer := "" footer := h.lp.SprintStyled("fg=bright-yellow", "[Enter]") + " Run " +
if h.leader != nil { h.lp.SprintStyled("fg=bright-yellow", "[Esc]") + " Quit " +
footer = h.lp.SprintStyled("fg=bright-yellow", "[Esc]") + " Close " + h.lp.SprintStyled("fg=bright-yellow", "\u2191\u2193") + " Navigate " +
h.lp.SprintStyled("fg=bright-yellow", "\u2191\u2193") + " Navigate " + h.lp.SprintStyled("fg=bright-yellow", "[F12]") + " " + unmappedToggleLabel + " unmapped"
h.lp.SprintStyled("fg=bright-yellow", "[Enter]") + " Run or press the next key"
} else if h.remap_mode {
footer = h.lp.SprintStyled("fg=bright-yellow", "Press the new shortcut") + " " +
h.lp.SprintStyled("fg=bright-yellow", "[Esc]") + " Cancel"
} else {
if !h.read_only {
footer = h.lp.SprintStyled("fg=bright-yellow", "[Enter]") + " Run "
}
footer += h.lp.SprintStyled("fg=bright-yellow", "[Esc]") + " Quit " +
h.lp.SprintStyled("fg=bright-yellow", "\u2191\u2193") + " Navigate " +
h.lp.SprintStyled("fg=bright-yellow", "[F12]") + " " + unmappedToggleLabel + " unmapped"
if !h.read_only {
footer += " " + h.lp.SprintStyled("fg=bright-yellow", "[Ctrl+R]") + " Remap"
}
}
matchCount := "" matchCount := ""
if h.query != "" { if h.query != "" {
matchCount = fmt.Sprintf(" %d/%d", len(h.filtered_idx), len(h.all_items)) matchCount = fmt.Sprintf(" %d/%d", len(h.filtered_idx), len(h.all_items))
@@ -788,9 +662,7 @@ func (h *Handler) drawFlatResults(startY, maxRows, width int) {
b := &item.binding b := &item.binding
keyDisplay := keyDisplayText(b) keyDisplay := keyDisplayText(b)
catSuffix := "" catSuffix := ""
if h.leader != nil { if b.Mode != "" {
// Leader rows have no category to disambiguate.
} else if b.Mode != "" {
catSuffix = fmt.Sprintf(" [%s/%s]", b.Mode, b.Category) catSuffix = fmt.Sprintf(" [%s/%s]", b.Mode, b.Category)
} else { } else {
catSuffix = fmt.Sprintf(" [%s]", b.Category) catSuffix = fmt.Sprintf(" [%s]", b.Category)
@@ -903,9 +775,8 @@ func (h *Handler) drawBindingLine(filteredIdx, width int, isSelected bool) {
b := &h.all_items[idx].binding b := &h.all_items[idx].binding
actionDisplay := h.all_items[idx].actionText actionDisplay := h.all_items[idx].actionText
// Build the key display, bounded by the room the panel leaves as well // Build the key display
keyWidth := keyWidthFor(width) keyDisplay := keyDisplayText(b)
keyDisplay := truncateToWidth(keyDisplayText(b), keyWidth)
// Determine match info for highlighting (only set when a query is active) // Determine match info for highlighting (only set when a query is active)
var mi *matchInfo var mi *matchInfo
@@ -934,8 +805,8 @@ func (h *Handler) drawBindingLine(filteredIdx, width int, isSelected bool) {
return s return s
} }
// Render key column (4-space indent + key padded to the key column width) // Render key column (4-space indent + key padded to maxKeyDisplayWidth + space)
paddingLen := max(0, keyWidth-wcswidth.Stringwidth(keyDisplay)) paddingLen := max(0, maxKeyDisplayWidth-wcswidth.Stringwidth(keyDisplay))
pad := strings.Repeat(" ", paddingLen) + " " pad := strings.Repeat(" ", paddingLen) + " "
ks := keyStyle ks := keyStyle
if b.Key == "" { if b.Key == "" {
@@ -949,8 +820,7 @@ func (h *Handler) drawBindingLine(filteredIdx, width int, isSelected bool) {
h.lp.QueueWriteString(h.lp.SprintStyled(ks, " "+keyDisplay+pad)) h.lp.QueueWriteString(h.lp.SprintStyled(ks, " "+keyDisplay+pad))
} }
// Render action display column, bounded by the room the panel leaves // Render action display column
actionDisplay = truncateToWidth(actionDisplay, h.actionColumnWidth(width, b))
if mi != nil && len(mi.actionPositions) > 0 { if mi != nil && len(mi.actionPositions) > 0 {
h.lp.QueueWriteString(h.highlightMatchedChars(actionDisplay, mi.actionPositions, baseStyle, matchStyle)) h.lp.QueueWriteString(h.highlightMatchedChars(actionDisplay, mi.actionPositions, baseStyle, matchStyle))
} else { } else {
@@ -958,14 +828,14 @@ func (h *Handler) drawBindingLine(filteredIdx, width int, isSelected bool) {
} }
// Render category suffix (only present in flat / search-results mode) // Render category suffix (only present in flat / search-results mode)
if h.query != "" && h.leader == nil { if h.query != "" {
h.drawCategorySuffix(b, mi, baseStyle, matchStyle) h.drawCategorySuffix(b, mi, baseStyle, matchStyle)
} }
// For selected rows, pad the rest of the line with reverse video // For selected rows, pad the rest of the line with reverse video
if isSelected { if isSelected {
rendered := 4 + wcswidth.Stringwidth(keyDisplay) + paddingLen + 1 + wcswidth.Stringwidth(actionDisplay) rendered := 4 + wcswidth.Stringwidth(keyDisplay) + paddingLen + 1 + wcswidth.Stringwidth(actionDisplay)
if h.query != "" && h.leader == nil { if h.query != "" {
rendered += categorySuffixWidth(b) rendered += categorySuffixWidth(b)
} }
if pad := width - rendered; pad > 0 { if pad := width - rendered; pad > 0 {
@@ -974,19 +844,6 @@ func (h *Handler) drawBindingLine(filteredIdx, width int, isSelected bool) {
} }
} }
// selectedActionText returns the action text of the selected row, which is the
// full name even when the row has to ellipsize it.
func (h *Handler) selectedActionText() string {
if h.selected_idx < 0 || h.selected_idx >= len(h.filtered_idx) {
return ""
}
idx := h.filtered_idx[h.selected_idx]
if idx < 0 || idx >= len(h.all_items) {
return ""
}
return h.all_items[idx].actionText
}
// rowToFilteredIdx converts a 0-indexed cell Y coordinate to a filtered item // rowToFilteredIdx converts a 0-indexed cell Y coordinate to a filtered item
// index, or -1 if the cell is not over a clickable item. Internally converts // index, or -1 if the cell is not over a clickable item. Internally converts
// to 1-indexed screen rows (matching the MoveCursorTo convention) to compare // to 1-indexed screen rows (matching the MoveCursorTo convention) to compare
@@ -1026,25 +883,6 @@ func (h *Handler) onMouseEvent(ev *loop.MouseEvent) error {
// onKeyEvent handles keyboard input for navigation, selection, and query editing. // onKeyEvent handles keyboard input for navigation, selection, and query editing.
func (h *Handler) onKeyEvent(ev *loop.KeyEvent) error { func (h *Handler) onKeyEvent(ev *loop.KeyEvent) error {
if h.remap_mode {
ev.Handled = true
if ev.MatchesPressOrRepeat("escape") || ev.MatchesPressOrRepeat("ctrl+c") {
h.remap_mode, h.remap_binding = false, nil
h.draw_screen()
return nil
}
if ev.Type&(loop.PRESS|loop.REPEAT) == 0 {
return nil
}
spec := keySpecForRemap(ev)
if spec == "" || h.remap_binding == nil {
h.lp.Beep()
return nil
}
h.remap_key, h.remap_action = spec, h.remap_binding.Definition
h.lp.Quit(0)
return nil
}
if ev.MatchesPressOrRepeat("escape") { if ev.MatchesPressOrRepeat("escape") {
ev.Handled = true ev.Handled = true
if h.query != "" { if h.query != "" {
@@ -1125,24 +963,6 @@ func (h *Handler) onKeyEvent(ev *loop.KeyEvent) error {
} }
return nil return nil
} }
if ev.MatchesPressOrRepeat("ctrl+r") && !h.read_only && h.leader == nil {
ev.Handled = true
if b := h.selectedBinding(); b != nil && !b.IsMouse {
h.remap_mode, h.remap_binding = true, b
h.draw_screen()
} else {
h.lp.Beep()
}
return nil
}
if h.leader != nil {
if b := h.matchLeaderBinding(ev); b != nil {
ev.Handled = true
h.leader_trigger(b)
return nil
}
return nil
}
if ev.MatchesPressOrRepeat("f12") { if ev.MatchesPressOrRepeat("f12") {
ev.Handled = true ev.Handled = true
h.show_unmapped = !h.show_unmapped h.show_unmapped = !h.show_unmapped
@@ -1157,19 +977,8 @@ func (h *Handler) onKeyEvent(ev *loop.KeyEvent) error {
return nil return nil
} }
// onText handles typed characters, appending them to the search query, or // onText handles typed characters, appending them to the search query.
// running the binding whose key was typed in the leader panel.
func (h *Handler) onText(text string, from_key_event bool, in_bracketed_paste bool) error { func (h *Handler) onText(text string, from_key_event bool, in_bracketed_paste bool) error {
if h.leader != nil {
for i := range h.all_items {
if b := &h.all_items[i].binding; b.Key != "" && strings.EqualFold(b.Key, text) {
h.leader_trigger(b)
return nil
}
}
h.lp.Beep()
return nil
}
h.query += text h.query += text
h.updateFilter() h.updateFilter()
h.draw_screen() h.draw_screen()
@@ -1194,55 +1003,8 @@ func (h *Handler) moveSelection(delta int) {
h.draw_screen() h.draw_screen()
} }
// matchLeaderBinding finds the leader entry whose key matches the event.
func (h *Handler) matchLeaderBinding(ev *loop.KeyEvent) *Binding {
for i := range h.all_items {
if b := &h.all_items[i].binding; b.Key != "" && ev.MatchesPressOrRepeat(b.Key) {
return b
}
}
return nil
}
// leader_trigger runs a leader entry immediately, without waiting for the rest
// of a longer multi-key sequence.
func (h *Handler) leader_trigger(b *Binding) {
h.result = b.Definition
h.lp.Quit(0)
}
// keySpecForRemap renders a key event in kitty.conf syntax so that the palette
// can write a map directive for it.
func keySpecForRemap(ev *loop.KeyEvent) string {
mods := ev.Mods.WithoutLocks()
parts := make([]string, 0, 4)
for _, m := range []struct {
mod loop.KeyModifiers
name string
}{{loop.CTRL, "ctrl"}, {loop.ALT, "alt"}, {loop.SHIFT, "shift"}, {loop.SUPER, "super"}, {loop.HYPER, "hyper"}, {loop.META, "meta"}} {
if mods&m.mod != 0 {
parts = append(parts, m.name)
}
}
key := ev.Key
if key == "" {
key = ev.Text
}
if key == "" {
return ""
}
if len(key) == 1 && key[0] >= 'A' && key[0] <= 'Z' {
key = strings.ToLower(key)
}
return strings.Join(append(parts, key), "+")
}
// triggerSelected sets the selected binding's definition as the result and exits. // triggerSelected sets the selected binding's definition as the result and exits.
func (h *Handler) triggerSelected() { func (h *Handler) triggerSelected() {
if h.read_only {
h.lp.Beep()
return
}
b := h.selectedBinding() b := h.selectedBinding()
if b == nil || b.IsMouse { if b == nil || b.IsMouse {
h.lp.Beep() h.lp.Beep()
@@ -1254,7 +1016,7 @@ func (h *Handler) triggerSelected() {
// main runs the command palette TUI as a kitty overlay. // main runs the command palette TUI as a kitty overlay.
func main(cmd *cli.Command, opts *Options, args []string) (rc int, err error) { func main(cmd *cli.Command, opts *Options, args []string) (rc int, err error) {
if opts.DataFile == "" && tty.IsTerminal(os.Stdin.Fd()) { if tty.IsTerminal(os.Stdin.Fd()) {
return 1, fmt.Errorf("This kitten must only be run via the command_palette action mapped to a shortcut in kitty.conf") return 1, fmt.Errorf("This kitten must only be run via the command_palette action mapped to a shortcut in kitty.conf")
} }
output := tui.KittenOutputSerializer() output := tui.KittenOutputSerializer()
@@ -1263,7 +1025,7 @@ func main(cmd *cli.Command, opts *Options, args []string) (rc int, err error) {
return 1, err return 1, err
} }
handler := &Handler{lp: lp, read_only: opts.ReadOnly, data_file: opts.DataFile} handler := &Handler{lp: lp}
lp.MouseTrackingMode(loop.FULL_MOUSE_TRACKING) lp.MouseTrackingMode(loop.FULL_MOUSE_TRACKING)
lp.OnInitialize = func() (string, error) { lp.OnInitialize = func() (string, error) {
@@ -1286,12 +1048,7 @@ func main(cmd *cli.Command, opts *Options, args []string) (rc int, err error) {
return return
} }
rc = lp.ExitCode() rc = lp.ExitCode()
if handler.remap_key != "" { if handler.result != "" {
s, serr := output(map[string]string{"remap_key": handler.remap_key, "remap_action": handler.remap_action})
if serr == nil {
fmt.Println(s)
}
} else if handler.result != "" {
s, serr := output(map[string]string{"action": handler.result}) s, serr := output(map[string]string{"action": handler.result})
if serr == nil { if serr == nil {
fmt.Println(s) fmt.Println(s)
+1 -70
View File
@@ -318,52 +318,6 @@ def collect_keys_data(opts: Any) -> dict[str, Any]:
} }
def collect_leader_data(opts: Any, prefix: Any, definitions: Any = None) -> dict[str, Any]:
"""Build the data for the leader/which-key panel from sequence mappings.
Only the first key after the leader is listed: that is the key the user has
to press next, matching how which-key panels present prefix trees. When the
mapping needs more keys, the full definition is still shown in the action
column and selecting it runs the action directly.
"""
from kitty.types import Shortcut
action_to_group, action_to_help, action_to_long_help = build_action_lookups()
if definitions is None:
definitions = []
for defns in opts.keyboard_modes[''].keymap.values():
for d in defns:
if d.is_sequence and d.trigger == prefix:
definitions.append(d)
bindings: list[dict[str, str]] = []
seen: set[str] = set()
for d in definitions:
if not d.is_sequence or not d.rest:
continue
key_repr = Shortcut((d.rest[0],)).human_repr(opts.kitty_mod)
if key_repr in seen:
continue
seen.add(key_repr)
action_name, category, alias = classify_action(d.definition, opts.alias_map, action_to_group)
entry: dict[str, str] = {
'key': key_repr,
'action': action_name,
'action_display': d.human_repr(),
'definition': d.definition,
'help': action_to_help.get(action_name, ''),
'long_help': action_to_long_help.get(action_name, ''),
'category': category,
}
if alias:
entry['alias'] = alias
bindings.append(entry)
bindings.sort(key=lambda b: b['key'])
prefix_repr = Shortcut((prefix,)).human_repr(opts.kitty_mod) if prefix is not None else ''
title = f'Leader keys ({prefix_repr})' if prefix_repr else 'Leader keys'
return {'leader': {'prefix': prefix_repr, 'title': title, 'bindings': bindings}}
def main(args: list[str]) -> None: def main(args: list[str]) -> None:
raise SystemExit('This kitten must be used only from a kitty.conf mapping') raise SystemExit('This kitten must be used only from a kitty.conf mapping')
@@ -376,21 +330,7 @@ def callback(target_window_id: int, action: str, timer_id: int | None) -> None:
@result_handler(has_ready_notification=True) @result_handler(has_ready_notification=True)
def handle_result(args: list[str], data: dict[str, Any], target_window_id: int, boss: BossType) -> None: def handle_result(args: list[str], data: dict[str, Any], target_window_id: int, boss: BossType) -> None:
if not data: if data and (action := data.get('action')):
return
remap_key, remap_action = data.get('remap_key'), data.get('remap_action')
if remap_key and remap_action:
from kitty.config import append_map_to_config
try:
path = append_map_to_config(remap_key, remap_action)
boss.load_config_file()
except Exception as err:
boss.show_error('Failed to remap shortcut', f'Could not update {remap_key} in the config file: {err}')
else:
print(f'Mapped {remap_key} to {remap_action} in {path}', flush=True)
return
if action := data.get('action'):
# run action after event loop tick so command palette overlay is closed # run action after event loop tick so command palette overlay is closed
add_timer(partial(callback, target_window_id, action), 0, False) add_timer(partial(callback, target_window_id, action), 0, False)
@@ -398,15 +338,6 @@ def handle_result(args: list[str], data: dict[str, Any], target_window_id: int,
help_text = 'Browse and trigger keyboard shortcuts and actions' help_text = 'Browse and trigger keyboard shortcuts and actions'
usage = '' usage = ''
OPTIONS = r""" OPTIONS = r"""
--data-file
Read keybinding data from this JSON file instead of STDIN. Used by the
keyboard shortcuts help panel, so that it can run in a dock window.
--read-only
type=bool-set
Display the bindings without running the selected action on Enter. The panel
is then a reference, not a launcher.
""".format """.format
+7 -133
View File
@@ -5,9 +5,6 @@ import (
"fmt" "fmt"
"strings" "strings"
"testing" "testing"
"github.com/kovidgoyal/kitty/tools/tui/loop"
"github.com/kovidgoyal/kitty/tools/wcswidth"
) )
// testBinding creates a Binding where Action, ActionDisplay, and Definition all // testBinding creates a Binding where Action, ActionDisplay, and Definition all
@@ -77,26 +74,6 @@ func (b *testHandlerBuilder) build() *Handler {
return h return h
} }
func TestParseData(t *testing.T) {
h := &Handler{}
data := []byte(`{"modes":{"":{"Cat":[{"key":"a","action":"x","action_display":"x","definition":"x"}]}},"mouse":[],"mode_order":[""],"category_order":{"":["Cat"]}}`)
if err := h.parseData(data); err != nil {
t.Fatal(err)
}
if len(h.all_items) != 1 {
t.Fatalf("expected 1 item, got %d", len(h.all_items))
}
if b := h.all_items[0].binding; b.Key != "a" || b.Category != "Cat" {
t.Fatalf("unexpected binding: %+v", b)
}
}
func TestParseDataRejectsEmptyInput(t *testing.T) {
if err := (&Handler{}).parseData(nil); err == nil {
t.Fatal("expected an error for empty data")
}
}
func newTestHandler() *Handler { func newTestHandler() *Handler {
return newBuilder(). return newBuilder().
addBinding("", "Copy/paste", testBinding("ctrl+shift+c", "copy_to_clipboard", "Copy the selected text from the active window to the clipboard")). addBinding("", "Copy/paste", testBinding("ctrl+shift+c", "copy_to_clipboard", "Copy the selected text from the active window to the clipboard")).
@@ -123,48 +100,6 @@ func newTestHandler() *Handler {
build() build()
} }
func TestLeaderPanel(t *testing.T) {
h := &Handler{}
data := []byte(`{"leader":{"prefix":"ctrl+space","title":"Leader keys","bindings":[{"key":"n","action":"new_os_window","action_display":"new_os_window","definition":"new_os_window"},{"key":"shift+w","action":"new_window","action_display":"new_window","definition":"new_window"}]}}`)
if err := h.parseData(data); err != nil {
t.Fatal(err)
}
if h.leader == nil {
t.Fatal("expected leader mode to be active")
}
if len(h.all_items) != 2 {
t.Fatalf("expected 2 leader entries, got %d", len(h.all_items))
}
if b := h.matchLeaderBinding(&loop.KeyEvent{Type: loop.PRESS, Key: "n"}); b == nil || b.Definition != "new_os_window" {
t.Fatalf("expected n to run new_os_window, got %+v", b)
}
if b := h.matchLeaderBinding(&loop.KeyEvent{Type: loop.PRESS, Key: "w", Mods: loop.SHIFT, ShiftedKey: "W"}); b == nil || b.Definition != "new_window" {
t.Fatalf("expected shift+w to run new_window, got %+v", b)
}
if b := h.matchLeaderBinding(&loop.KeyEvent{Type: loop.PRESS, Key: "x"}); b != nil {
t.Fatalf("expected x to match nothing, got %+v", b)
}
}
func TestKeySpecForRemap(t *testing.T) {
cases := []struct {
ev loop.KeyEvent
expected string
}{
{loop.KeyEvent{Type: loop.PRESS, Key: "a"}, "a"},
{loop.KeyEvent{Type: loop.PRESS, Key: "a", Mods: loop.SHIFT}, "shift+a"},
{loop.KeyEvent{Type: loop.PRESS, Key: "a", Mods: loop.CTRL | loop.SHIFT}, "ctrl+shift+a"},
{loop.KeyEvent{Type: loop.PRESS, Key: "a", Mods: loop.CTRL | loop.CAPS_LOCK}, "ctrl+a"},
{loop.KeyEvent{Type: loop.PRESS, Key: "", Text: "é"}, "é"},
{loop.KeyEvent{Type: loop.PRESS, Key: "", Text: ""}, ""},
}
for _, c := range cases {
if got := keySpecForRemap(&c.ev); got != c.expected {
t.Fatalf("keySpecForRemap(%+v) = %q, expected %q", c.ev, got, c.expected)
}
}
}
func TestFlattenAllBindings(t *testing.T) { func TestFlattenAllBindings(t *testing.T) {
h := newTestHandler() h := newTestHandler()
// 5 default mode + 2 mw mode + 2 mouse = 9 // 5 default mode + 2 mw mode + 2 mouse = 9
@@ -436,13 +371,13 @@ func TestTruncateToWidth(t *testing.T) {
t.Fatalf("Expected %q unchanged at exact width, got %q", "hello", got) t.Fatalf("Expected %q unchanged at exact width, got %q", "hello", got)
} }
// Over width: truncated with a single cell ellipsis // Over width: truncated with ellipsis
got = truncateToWidth("hello world", 8) got = truncateToWidth("hello world", 8)
if !strings.HasSuffix(got, ellipsis) { if !strings.HasSuffix(got, "...") {
t.Fatalf("Expected truncated string to end with %q, got %q", ellipsis, got) t.Fatalf("Expected truncated string to end with '...', got %q", got)
} }
if wcswidth.Stringwidth(got) > 8 { if len([]rune(got)) > 8 {
t.Fatalf("Expected truncated string to be at most 8 cells, got %d in %q", wcswidth.Stringwidth(got), got) t.Fatalf("Expected truncated string to be at most 8 runes, got %d in %q", len([]rune(got)), got)
} }
// Long key like a mouse binding should be truncated // Long key like a mouse binding should be truncated
@@ -451,69 +386,8 @@ func TestTruncateToWidth(t *testing.T) {
if len([]rune(got)) > maxKeyDisplayWidth { if len([]rune(got)) > maxKeyDisplayWidth {
t.Fatalf("Key should be truncated to maxKeyDisplayWidth, got len=%d: %q", len([]rune(got)), got) t.Fatalf("Key should be truncated to maxKeyDisplayWidth, got len=%d: %q", len([]rune(got)), got)
} }
if !strings.HasSuffix(got, ellipsis) { if !strings.HasSuffix(got, "...") {
t.Fatalf("Truncated key should end with %q, got %q", ellipsis, got) t.Fatalf("Truncated key should end with '...', got %q", got)
}
}
func TestActionColumnStaysInsideThePanel(t *testing.T) {
h := newTestHandler()
b := testBinding("ctrl+shift+alt+v", "paste_from_clipboard_history", "Paste an entry from the clipboard history")
b.Category = "Copy/paste"
const width = 50
// Without a query there is no category suffix, so the whole rest of the row
// belongs to the action
keyColumnWidth := keyColumnWidthFor(width)
budget := h.actionColumnWidth(width, &b)
if budget != width-keyColumnWidth {
t.Fatalf("Expected %d cells for the action, got %d", width-keyColumnWidth, budget)
}
// Search results reserve the room the category suffix needs
h.query = "paste"
budget = h.actionColumnWidth(width, &b)
if want := width - keyColumnWidth - categorySuffixWidth(&b); budget != want {
t.Fatalf("Expected %d cells for the action next to the suffix, got %d", want, budget)
}
// A long name is ellipsized within its own column rather than cut by the edge
got := truncateToWidth(b.ActionDisplay, budget)
if w := wcswidth.Stringwidth(got); w > budget {
t.Fatalf("Action display is %d cells, over the %d cell column: %q", w, budget, got)
}
if !strings.HasSuffix(got, ellipsis) {
t.Fatalf("Expected the action display to be ellipsized, got %q", got)
}
// A name that fits is left untouched
short := testBinding("ctrl+shift+c", "copy_to_clipboard", "Copy")
const wideWidth = 80
if got := truncateToWidth(short.ActionDisplay, h.actionColumnWidth(wideWidth, &short)); got != short.ActionDisplay {
t.Fatalf("Expected %q unchanged, got %q", short.ActionDisplay, got)
}
}
func TestRowFitsInNarrowPanel(t *testing.T) {
h := newTestHandler()
h.query = "paste"
b := testBinding("ctrl+shift+alt+v press", "paste_from_clipboard_history", "Paste an entry")
b.Category = "Copy/paste"
for _, width := range []int{10, 20, 35, 50, 104} {
keyWidth := keyWidthFor(width)
key := truncateToWidth(keyDisplayText(&b), keyWidth)
action := truncateToWidth(b.ActionDisplay, h.actionColumnWidth(width, &b))
row := 4 + wcswidth.Stringwidth(key) + max(0, keyWidth-wcswidth.Stringwidth(key)) + 1 + wcswidth.Stringwidth(action)
if row > width {
t.Fatalf("Row is %d cells wide in a %d cell panel: key %q action %q", row, width, key, action)
}
}
// The key column only shrinks when the panel cannot hold the full one
if keyWidthFor(104) != maxKeyDisplayWidth {
t.Fatalf("Expected the full key column on a wide panel, got %d", keyWidthFor(104))
}
if keyWidthFor(20) >= maxKeyDisplayWidth {
t.Fatalf("Expected the key column to shrink on a narrow panel, got %d", keyWidthFor(20))
} }
} }
+8 -168
View File
@@ -80,17 +80,7 @@ func read_dir(dir string, show_hidden bool, sort_by string) ([]Entry, error) {
continue continue
} }
e := Entry{Name: name, IsDir: item.IsDir()} e := Entry{Name: name, IsDir: item.IsDir()}
info, ierr := item.Info() if info, ierr := item.Info(); ierr == nil {
if item.Type()&os.ModeSymlink != 0 {
// A symlink is reported as its own type, so a link to a directory
// would be opened in the editor instead of being browsed. Follow
// it to classify the entry; broken links stay plain entries.
if target, terr := os.Stat(filepath.Join(dir, name)); terr == nil {
info, ierr = target, nil
e.IsDir = target.IsDir()
}
}
if ierr == nil {
e.ModTime = info.ModTime().Unix() e.ModTime = info.ModTime().Unix()
e.Size = info.Size() e.Size = info.Size()
} }
@@ -100,23 +90,6 @@ func read_dir(dir string, show_hidden bool, sort_by string) ([]Entry, error) {
return entries, nil return entries, nil
} }
// expand_home expands a leading ~ so that a directory given in a mapping or by
// the remote control API, where no shell expands it, names the same directory
// as it would on the command line.
func expand_home(path string) (string, error) {
if path != "~" && !strings.HasPrefix(path, "~/") {
return path, nil
}
home, err := os.UserHomeDir()
if err != nil {
return "", err
}
if path == "~" {
return home, nil
}
return filepath.Join(home, path[2:]), nil
}
func entry_path(dir, name string) string { func entry_path(dir, name string) string {
return filepath.Join(dir, name) return filepath.Join(dir, name)
} }
@@ -196,10 +169,6 @@ func resolve_start_dir(candidate string) (string, error) {
} }
candidate = cwd candidate = cwd
} }
candidate, err := expand_home(candidate)
if err != nil {
return "", err
}
abs, err := filepath.Abs(candidate) abs, err := filepath.Abs(candidate)
if err != nil { if err != nil {
return "", err return "", err
@@ -228,28 +197,6 @@ func truncate_to_width(s string, max_width int) string {
return string(runes) + "\u2026" return string(runes) + "\u2026"
} }
// wheel_scroll_lines is the number of rows one wheel notch scrolls. It sits
// between a single line, which makes a long directory tedious, and the default
// kitty wheel_scroll_multiplier of five, which skips too much in a panel.
const wheel_scroll_lines = 3
// double_click_interval is the largest gap between two clicks on the same row
// that still counts as a double click, matching kitty's click_interval default.
const double_click_interval = 500 * time.Millisecond
// click_tracker remembers the last click so that a second click on the same row
// opens it, while clicks on different rows stay single selections.
type click_tracker struct {
at time.Time
idx int
}
func (c *click_tracker) is_double(now time.Time, idx int) bool {
prev_at, prev_idx := c.at, c.idx
c.at, c.idx = now, idx
return idx == prev_idx && !prev_at.IsZero() && now.Sub(prev_at) <= double_click_interval
}
type Handler struct { type Handler struct {
lp *loop.Loop lp *loop.Loop
screen_size loop.ScreenSize screen_size loop.ScreenSize
@@ -274,10 +221,6 @@ type Handler struct {
result_path string result_path string
shortcut_tracker config.ShortcutTracker shortcut_tracker config.ShortcutTracker
keyboard_shortcuts []*config.KeyAction keyboard_shortcuts []*config.KeyAction
sync *shell_sync
sync_handled bool
sync_published bool
clicks click_tracker
} }
func (h *Handler) initialize() (string, error) { func (h *Handler) initialize() (string, error) {
@@ -292,69 +235,11 @@ func (h *Handler) initialize() (string, error) {
if err = h.load(h.cwd); err != nil { if err = h.load(h.cwd); err != nil {
return "", err return "", err
} }
if h.sync != nil {
// Adopt the directory the shell is already in as the reference point so
// that an explicit --start-dir is not overridden by the first tick.
h.sync.last = h.sync.shell_cwd()
if _, err = h.lp.AddTimer(400*time.Millisecond, true, func(loop.IdType) error {
h.follow_shell_cwd()
return nil
}); err != nil {
return "", err
}
}
h.draw_screen() h.draw_screen()
h.lp.SendOverlayReady() h.lp.SendOverlayReady()
return "", nil return "", nil
} }
// publish_browse hands the directory the user just opened in the panel to the
// shell, so that walking through the tree in the panel walks the shell through
// it too. The shell reads the request at its next prompt; until then the panel
// remembers it so that quitting can withdraw it.
func (h *Handler) publish_browse() {
if h.sync == nil || !h.sync.shell_has_hook() {
return
}
if err := h.sync.publish_request(h.cwd); err != nil {
return
}
h.sync_published = true
}
// withdraw_sync_request drops a request published by browsing, so that leaving
// the panel without validating a directory leaves the shell where it was. It
// does nothing once the shell has read the request, which it only does at a
// prompt.
func (h *Handler) withdraw_sync_request() {
if !h.sync_published {
return
}
h.sync.withdraw_request()
h.sync_published = false
}
// follow_shell_cwd mirrors a cd made in the shell into the panel, keeping the
// selection on the same name so that the cursor does not jump around.
func (h *Handler) follow_shell_cwd() {
if h.sync == nil {
return
}
dir := h.sync.new_target(h.cwd)
if dir == "" {
return
}
name := ""
if e, ok := h.selected_entry(); ok {
name = e.Name
}
if err := h.load(dir); err != nil {
return
}
h.select_name(name)
h.draw_screen()
}
// load reads dir and adopts it as the current directory. Selection is clamped // load reads dir and adopts it as the current directory. Selection is clamped
// rather than reset so that reloading a directory after an action keeps the // rather than reset so that reloading a directory after an action keeps the
// cursor near where it was. // cursor near where it was.
@@ -424,7 +309,6 @@ func (h *Handler) change_dir(dir string) {
} }
h.selected, h.scroll, h.message = 0, 0, "" h.selected, h.scroll, h.message = 0, 0, ""
h.draw_screen() h.draw_screen()
h.publish_browse()
} }
func (h *Handler) move_selection(delta int) { func (h *Handler) move_selection(delta int) {
@@ -599,8 +483,8 @@ func (h *Handler) open_file_in(path, window_type string) {
h.draw_screen() h.draw_screen()
} }
// enter_dir browses into the selected directory inside the panel and hands it to // enter_dir browses into the selected directory inside the panel, leaving the
// the shell, so that both stay on the same directory. // working directory of the shell untouched.
func (h *Handler) enter_dir() { func (h *Handler) enter_dir() {
e, ok := h.selected_entry() e, ok := h.selected_entry()
if !ok || !e.IsDir { if !ok || !e.IsDir {
@@ -612,14 +496,6 @@ func (h *Handler) enter_dir() {
func (h *Handler) change_shell_dir_to(path string) { func (h *Handler) change_shell_dir_to(path string) {
h.result_action, h.result_path = "cd", path h.result_action, h.result_path = "cd", path
// With the sync on, the shell reads the request from its session file at the
// next prompt, so the handler must not also type the change into its pty.
// The request is only written once the shell proved it has the hook by
// publishing its directory: a shell without shell integration would
// otherwise never see it and the change would be silently lost.
if h.sync != nil && h.sync.shell_has_hook() && h.sync.publish_request(path) == nil {
h.sync_handled = true
}
h.lp.Quit(0) h.lp.Quit(0)
} }
@@ -670,10 +546,7 @@ var action_catalog = []action_info{
// Actions that need the panel state are plain functions of the handler, so the // Actions that need the panel state are plain functions of the handler, so the
// palette and the configurable shortcuts go through the same code path. // palette and the configurable shortcuts go through the same code path.
var action_handlers = map[string]func(*Handler){ var action_handlers = map[string]func(*Handler){
"quit": func(h *Handler) { "quit": func(h *Handler) { h.lp.Quit(0) },
h.withdraw_sync_request()
h.lp.Quit(0)
},
"move_up": func(h *Handler) { h.move_selection(-1) }, "move_up": func(h *Handler) { h.move_selection(-1) },
"move_down": func(h *Handler) { h.move_selection(1) }, "move_down": func(h *Handler) { h.move_selection(1) },
"page_up": func(h *Handler) { "page_up": func(h *Handler) {
@@ -1111,42 +984,13 @@ func (h *Handler) row_to_entry(cell_y int) int {
} }
func (h *Handler) on_mouse_event(ev *loop.MouseEvent) error { func (h *Handler) on_mouse_event(ev *loop.MouseEvent) error {
// The palette owns the pointer while it is open, so clicks and wheel events
// do not change the selection behind it.
if h.palette_open && ev.Event_type != loop.MOUSE_MOVE {
return nil
}
switch ev.Event_type { switch ev.Event_type {
case loop.MOUSE_PRESS:
// Wheel notches arrive as presses carrying a wheel button. Moving the
// selection keeps the list scrolled to the row under it, without sending
// the event to the terminal that hosts the dock.
switch {
case ev.Buttons&loop.MOUSE_WHEEL_UP != 0:
h.move_selection(-wheel_scroll_lines)
case ev.Buttons&loop.MOUSE_WHEEL_DOWN != 0:
h.move_selection(wheel_scroll_lines)
}
case loop.MOUSE_CLICK: case loop.MOUSE_CLICK:
switch { if ev.Buttons&loop.LEFT_MOUSE_BUTTON != 0 {
case ev.Buttons&loop.LEFT_MOUSE_BUTTON != 0:
idx := h.row_to_entry(ev.Cell.Y)
if idx < 0 {
return nil
}
h.selected = idx
if h.clicks.is_double(time.Now(), idx) {
h.activate()
return nil
}
h.draw_screen()
case ev.Buttons&loop.RIGHT_MOUSE_BUTTON != 0:
// The context menu is the action palette that :: already opens, so
// every panel action is reachable from the pointer too.
if idx := h.row_to_entry(ev.Cell.Y); idx >= 0 { if idx := h.row_to_entry(ev.Cell.Y); idx >= 0 {
h.selected = idx h.selected = idx
h.draw_screen()
} }
h.open_palette()
} }
case loop.MOUSE_MOVE: case loop.MOUSE_MOVE:
h.lp.ClearPointerShapes() h.lp.ClearPointerShapes()
@@ -1292,11 +1136,7 @@ func (h *Handler) draw_screen() {
// result_payload is the JSON data handed over to the Python result handler. // result_payload is the JSON data handed over to the Python result handler.
func (h *Handler) result_payload() map[string]string { func (h *Handler) result_payload() map[string]string {
ans := map[string]string{"action": h.result_action, "path": h.result_path} return map[string]string{"action": h.result_action, "path": h.result_path}
if h.sync_handled {
ans["sync"] = "1"
}
return ans
} }
func load_config(opts *Options) (*Config, error) { func load_config(opts *Options) (*Config, error) {
@@ -1325,7 +1165,7 @@ func main(_ *cli.Command, opts *Options, args []string) (rc int, err error) {
if err != nil { if err != nil {
return 1, err return 1, err
} }
h := &Handler{lp: lp, conf: conf, cwd: start_dir, show_hidden: opts.ShowHidden || conf.Show_hidden, sync: new_shell_sync_from_env(conf.Sync_cwd)} h := &Handler{lp: lp, conf: conf, cwd: start_dir, show_hidden: opts.ShowHidden || conf.Show_hidden}
h.keyboard_shortcuts = config.ResolveShortcuts(conf.KeyboardShortcuts) h.keyboard_shortcuts = config.ResolveShortcuts(conf.KeyboardShortcuts)
lp.MouseTrackingMode(loop.FULL_MOUSE_TRACKING) lp.MouseTrackingMode(loop.FULL_MOUSE_TRACKING)
-27
View File
@@ -48,29 +48,6 @@ directories first, then files sorted by size, largest first.
egr() egr()
agr('shell', 'Shell synchronisation')
opt(
'sync_cwd',
'yes',
option_type='to_bool',
long_text="""
Keep the shell's working directory and the panel in step. A :code:`cd` in the
shell moves the panel to the same directory, and walking through the panel moves
the shell to the directory being browsed at its next prompt. Quitting the panel
without validating a directory withdraws a request the shell has not read yet.
The exchange goes through two small files in the session directory kitty
exports as :envvar:`KITTY_CWD_SYNC_DIR`, so nothing is typed into the shell:
the command never lands in the history and a half typed multi-line command is
left untouched. Bash, zsh and fish are supported by their kitty shell
integration; other shells keep the current behaviour. Set :code:`sync_cwd no`
to keep the two directories independent.
""",
)
egr()
agr('opening', 'Opening files') agr('opening', 'Opening files')
opt( opt(
@@ -242,10 +219,6 @@ def handle_result(args: list[str], data: dict[str, Any], target_window_id: int,
action, path = data.get('action'), data.get('path') action, path = data.get('action'), data.get('path')
if action != 'cd' or not path: if action != 'cd' or not path:
return return
if data.get('sync'):
# The panel published the directory in the session file and the shell
# picks it up from its prompt hook, see the sync_cwd option.
return
w = boss.window_id_map.get(target_window_id) w = boss.window_id_map.get(target_window_id)
if w is None: if w is None:
boss.ring_bell_if_allowed() boss.ring_bell_if_allowed()
+2 -139
View File
@@ -8,8 +8,6 @@ import (
"path/filepath" "path/filepath"
"testing" "testing"
"time" "time"
"github.com/kovidgoyal/kitty/tools/tui/loop"
) )
func TestSortEntriesDirectoriesFirstThenByName(t *testing.T) { func TestSortEntriesDirectoriesFirstThenByName(t *testing.T) {
@@ -82,66 +80,6 @@ func TestReadDirReportsErrors(t *testing.T) {
} }
} }
func TestReadDirAcceptsAnEmptyDirectory(t *testing.T) {
entries, err := read_dir(t.TempDir(), false, "name")
if err != nil {
t.Fatal(err)
}
if len(entries) != 0 {
t.Fatalf("an empty directory must list nothing, got %#v", entries)
}
}
func TestReadDirReportsPermissionDenied(t *testing.T) {
dir := t.TempDir()
if err := os.Chmod(dir, 0o000); err != nil {
t.Skipf("cannot change permissions: %v", err)
}
// Make the directory readable again before TempDir cleans it up.
defer os.Chmod(dir, 0o700) //nolint:errcheck
if _, err := read_dir(dir, false, "name"); err == nil {
t.Skip("the current user can read a mode 000 directory, probably running as root")
}
}
func TestReadDirTreatsSymlinkedDirectoryAsDirectory(t *testing.T) {
dir := t.TempDir()
if err := os.Mkdir(filepath.Join(dir, "target"), 0o755); err != nil {
t.Fatal(err)
}
if err := os.Symlink("target", filepath.Join(dir, "link")); err != nil {
t.Skipf("cannot create symlinks: %v", err)
}
entries, err := read_dir(dir, false, "name")
if err != nil {
t.Fatal(err)
}
for _, e := range entries {
if e.Name == "link" {
if !e.IsDir {
t.Fatal("a symlink to a directory must be browsable, not opened as a file")
}
return
}
}
t.Fatalf("the symlink is missing from the listing: %#v", entries)
}
func TestReadDirHandlesNonUTF8Names(t *testing.T) {
dir := t.TempDir()
name := string([]byte{'b', 'a', 'd', 0xff, '.', 't', 'x', 't'})
if err := os.WriteFile(filepath.Join(dir, name), nil, 0o644); err != nil {
t.Skipf("the filesystem rejects non-UTF-8 names: %v", err)
}
entries, err := read_dir(dir, false, "name")
if err != nil {
t.Fatal(err)
}
if len(entries) != 1 || entries[0].Name != name {
t.Fatalf("the non-UTF-8 name must be listed unchanged, got %#v", entries)
}
}
func TestValidateEntryName(t *testing.T) { func TestValidateEntryName(t *testing.T) {
for _, name := range []string{"", ".", "..", "a/b", "a\x00b"} { for _, name := range []string{"", ".", "..", "a/b", "a\x00b"} {
if err := validate_entry_name(name); err == nil { if err := validate_entry_name(name); err == nil {
@@ -210,22 +148,6 @@ func TestCreateRenameAndDelete(t *testing.T) {
} }
} }
func TestResolveStartDirExpandsHome(t *testing.T) {
home := t.TempDir()
projects := filepath.Join(home, "projects")
if err := os.Mkdir(projects, 0o755); err != nil {
t.Fatal(err)
}
t.Setenv("HOME", home)
got, err := resolve_start_dir("~/projects")
if err != nil {
t.Fatal(err)
}
if got != projects {
t.Fatalf("resolve_start_dir(~/projects) = %q, wanted %q", got, projects)
}
}
func TestResolveStartDirAcceptsFiles(t *testing.T) { func TestResolveStartDirAcceptsFiles(t *testing.T) {
dir := t.TempDir() dir := t.TempDir()
file := filepath.Join(dir, "file.txt") file := filepath.Join(dir, "file.txt")
@@ -260,19 +182,6 @@ func TestOpenWithSudoOption(t *testing.T) {
} }
} }
func TestSyncCwdIsOnByDefault(t *testing.T) {
c := NewConfig()
if !c.Sync_cwd {
t.Fatal("the panel must follow the shell by default")
}
if err := c.Parse("sync_cwd", "no"); err != nil {
t.Fatal(err)
}
if c.Sync_cwd {
t.Fatal("sync_cwd = no must keep the two directories independent")
}
}
func TestEditArgs(t *testing.T) { func TestEditArgs(t *testing.T) {
got := edit_args("/tmp/a.py") got := edit_args("/tmp/a.py")
want := []string{"edit-in-kitty", "--type=tab", "/tmp/a.py"} want := []string{"edit-in-kitty", "--type=tab", "/tmp/a.py"}
@@ -376,13 +285,8 @@ func TestFilterEntriesLargeDirectory(t *testing.T) {
if len(matches) == 0 { if len(matches) == 0 {
t.Fatal("expected matches in a large directory") t.Fatal("expected matches in a large directory")
} }
// The bound is deliberately loose: this guards against the filter becoming if elapsed > 100*time.Millisecond {
// superlinear (which turns 10000 entries into seconds), not against a few t.Fatalf("filtering 10000 entries took %s, the limit is 100ms", elapsed)
// extra milliseconds. A wall clock threshold tight enough to measure the
// current implementation fails on a shared machine, where the same test
// went from 15ms to 147ms while makepkg was building next to it.
if elapsed > time.Second {
t.Fatalf("filtering 10000 entries took %s, the limit is 1s", elapsed)
} }
} }
@@ -437,47 +341,6 @@ func TestEditArgsInWindow(t *testing.T) {
} }
} }
func TestRowToEntryAccountsForScroll(t *testing.T) {
h := &Handler{
screen_size: loop.ScreenSize{WidthCells: 40, HeightCells: 10},
entries: make([]Entry, 12),
scroll: 3,
}
// The list starts on row 2 and the status line takes the last row, so rows
// 2..8 display entries 3..9
cases := map[int]int{0: -1, 1: 3, 4: 6, 7: 9, 8: -1, 9: -1}
for cell_y, want := range cases {
if got := h.row_to_entry(cell_y); got != want {
t.Fatalf("cell Y %d: wanted entry %d, got %d", cell_y, want, got)
}
}
// A scroll past the end of the list maps to no entry rather than panicking
h.scroll = 20
if got := h.row_to_entry(1); got != -1 {
t.Fatalf("wanted no entry past the end of the list, got %d", got)
}
}
func TestClickTrackerDetectsDoubleClick(t *testing.T) {
start := time.Unix(1000, 0)
var c click_tracker
if c.is_double(start, 2) {
t.Fatal("a first click must not be a double click")
}
if !c.is_double(start.Add(200*time.Millisecond), 2) {
t.Fatal("a second click on the same row within the interval is a double click")
}
if c.is_double(start.Add(5*time.Second), 2) {
t.Fatal("a click after the interval must not be a double click")
}
if c.is_double(start.Add(5*time.Second+100*time.Millisecond), 7) {
t.Fatal("a click on another row must not be a double click")
}
if !c.is_double(start.Add(5*time.Second+200*time.Millisecond), 7) {
t.Fatal("the tracker must accept the row clicked last")
}
}
func TestTruncateToWidth(t *testing.T) { func TestTruncateToWidth(t *testing.T) {
if got := truncate_to_width("abcdef", 3); got != "ab\u2026" { if got := truncate_to_width("abcdef", 3); got != "ab\u2026" {
t.Fatalf("unexpected truncation %q", got) t.Fatalf("unexpected truncation %q", got)
-99
View File
@@ -1,99 +0,0 @@
// License: GPLv3 Copyright: 2026, FWS
package file_manager
import (
"os"
"path/filepath"
"strings"
)
// shell_sync is the file based channel between a shell and the panel. kitty
// exports KITTY_CWD_SYNC_DIR to every window and KITTY_SPECIAL_WINDOW_PARENT to
// the special windows it opens for another one, so both sides agree on two file
// names without a socket or a new protocol: the shell publishes its working
// directory in <dir>/<window id>, the panel publishes the directory it wants in
// <dir>/<window id>.set. The shell applies that request from its prompt hook,
// which keeps the command out of the history and leaves a half typed multi-line
// command alone.
type shell_sync struct {
dir string
window_id string
last string
}
func new_shell_sync(dir, window_id string, enabled bool) *shell_sync {
if !enabled || dir == "" || window_id == "" {
return nil
}
if info, err := os.Stat(dir); err != nil || !info.IsDir() {
return nil
}
return &shell_sync{dir: dir, window_id: window_id}
}
// new_shell_sync_from_env is nil whenever the option is off or kitty did not
// give the panel a shell window to talk to, in which case the panel keeps its
// own behaviour and types the change into the shell instead.
func new_shell_sync_from_env(enabled bool) *shell_sync {
return new_shell_sync(os.Getenv("KITTY_CWD_SYNC_DIR"), os.Getenv("KITTY_SPECIAL_WINDOW_PARENT"), enabled)
}
func (s *shell_sync) shell_cwd_path() string { return filepath.Join(s.dir, s.window_id) }
func (s *shell_sync) request_path() string { return s.shell_cwd_path() + ".set" }
// shell_has_hook reports whether the shell has published its working directory
// at least once, which only the integration hook does. Without it nothing would
// consume the request, so the panel has to type the change into the shell.
func (s *shell_sync) shell_has_hook() bool {
_, err := os.Stat(s.shell_cwd_path())
return err == nil
}
// shell_cwd returns the working directory last published by the shell. An empty
// or relative path, or one that no longer exists, is treated as unknown rather
// than followed, as the shell may be between two writes.
func (s *shell_sync) shell_cwd() string {
b, err := os.ReadFile(s.shell_cwd_path())
if err != nil {
return ""
}
p := strings.TrimSpace(string(b))
if !filepath.IsAbs(p) {
return ""
}
if info, err := os.Stat(p); err != nil || !info.IsDir() {
return ""
}
return p
}
// new_target returns the directory the panel should move to, or "" when the
// shell has not moved since the last call or already sits in current.
func (s *shell_sync) new_target(current string) string {
p := s.shell_cwd()
if p == "" || p == s.last {
return ""
}
s.last = p
if p == current {
return ""
}
return p
}
// publish_request hands a directory to the shell. The write goes through a
// temporary file so that the shell never reads a half written path.
func (s *shell_sync) publish_request(dir string) error {
tmp := s.request_path() + ".tmp"
if err := os.WriteFile(tmp, []byte(dir), 0o600); err != nil {
return err
}
return os.Rename(tmp, s.request_path())
}
// withdraw_request cancels a request the shell has not read yet. Removing a
// request it already consumed is not an error, the shell removes it itself.
func (s *shell_sync) withdraw_request() {
_ = os.Remove(s.request_path())
}
-150
View File
@@ -1,150 +0,0 @@
// License: GPLv3 Copyright: 2026, FWS
package file_manager
import (
"os"
"path/filepath"
"testing"
)
func TestNewShellSyncNeedsOptionDirectoryAndWindow(t *testing.T) {
dir := t.TempDir()
if s := new_shell_sync(dir, "7", false); s != nil {
t.Fatal("the sync must stay off until the option is enabled")
}
if s := new_shell_sync("", "7", true); s != nil {
t.Fatal("the sync must be off without a session directory")
}
if s := new_shell_sync(dir, "", true); s != nil {
t.Fatal("the sync must be off without a shell window id")
}
if s := new_shell_sync(filepath.Join(dir, "missing"), "7", true); s != nil {
t.Fatal("the sync must be off when the session directory is missing")
}
if s := new_shell_sync(dir, "7", true); s == nil {
t.Fatal("the sync must be on with an option, a directory and a window id")
}
}
func TestPublishRequestIsReadableAndLeavesNoTemporaryFile(t *testing.T) {
dir := t.TempDir()
s := new_shell_sync(dir, "42", true)
if err := s.publish_request("/tmp/target dir"); err != nil {
t.Fatal(err)
}
got, err := os.ReadFile(filepath.Join(dir, "42.set"))
if err != nil {
t.Fatal(err)
}
if string(got) != "/tmp/target dir" {
t.Fatalf("unexpected request payload %q", got)
}
if _, err = os.Stat(filepath.Join(dir, "42.set.tmp")); err == nil {
t.Fatal("the temporary file must be renamed, not left behind")
}
}
func TestShellHasHookNeedsAPublishedDirectory(t *testing.T) {
dir := t.TempDir()
s := new_shell_sync(dir, "5", true)
if s.shell_has_hook() {
t.Fatal("the shell published nothing yet")
}
if err := s.publish_request(dir); err != nil {
t.Fatal(err)
}
if s.shell_has_hook() {
t.Fatal("a request must not be mistaken for a published directory")
}
if err := os.WriteFile(filepath.Join(dir, "5"), []byte(dir), 0o600); err != nil {
t.Fatal(err)
}
if !s.shell_has_hook() {
t.Fatal("a published directory means the shell has the hook")
}
}
func TestPublishBrowseNeedsTheShellHookAndCanBeWithdrawn(t *testing.T) {
dir := t.TempDir()
h := &Handler{sync: new_shell_sync(dir, "11", true), cwd: dir}
h.publish_browse()
if _, err := os.Stat(filepath.Join(dir, "11.set")); err == nil {
t.Fatal("the panel must not publish before the shell proved it has the hook")
}
if h.sync_published {
t.Fatal("nothing was published")
}
if err := os.WriteFile(filepath.Join(dir, "11"), []byte(dir), 0o600); err != nil {
t.Fatal(err)
}
h.publish_browse()
if got, err := os.ReadFile(filepath.Join(dir, "11.set")); err != nil || string(got) != dir {
t.Fatalf("unexpected request %q (%v)", got, err)
}
if !h.sync_published {
t.Fatal("the request must be remembered so that quitting can withdraw it")
}
h.withdraw_sync_request()
if _, err := os.Stat(filepath.Join(dir, "11.set")); err == nil {
t.Fatal("quitting must withdraw the pending request")
}
if h.sync_published {
t.Fatal("nothing is pending anymore")
}
h.withdraw_sync_request()
}
func TestShellCwdIgnoresUnusablePaths(t *testing.T) {
dir := t.TempDir()
s := new_shell_sync(dir, "9", true)
published := filepath.Join(dir, "9")
for _, content := range []string{"", " \n", "relative/path", filepath.Join(dir, "gone")} {
if err := os.WriteFile(published, []byte(content), 0o600); err != nil {
t.Fatal(err)
}
if got := s.shell_cwd(); got != "" {
t.Fatalf("%q must not be followed, got %q", content, got)
}
}
if got := s.shell_cwd(); got != "" {
t.Fatalf("a missing file must not be followed, got %q", got)
}
}
func TestNewTargetFollowsEachShellMoveOnce(t *testing.T) {
dir := t.TempDir()
s := new_shell_sync(dir, "3", true)
moved := t.TempDir()
s.last = dir
if got := s.new_target(dir); got != "" {
t.Fatalf("the shell has not moved yet, got %q", got)
}
if err := os.WriteFile(filepath.Join(dir, "3"), []byte(moved), 0o600); err != nil {
t.Fatal(err)
}
if got := s.new_target(dir); got != moved {
t.Fatalf("wanted %q, got %q", moved, got)
}
if got := s.new_target(dir); got != "" {
t.Fatalf("a shell move must only be followed once, got %q", got)
}
if err := os.WriteFile(filepath.Join(dir, "3"), []byte(dir), 0o600); err != nil {
t.Fatal(err)
}
if got := s.new_target(dir); got != "" {
t.Fatalf("moving to the directory already displayed must be a no-op, got %q", got)
}
}
func TestResultPayloadAdvertisesSyncOnlyWhenHandled(t *testing.T) {
h := &Handler{result_action: "cd", result_path: "/tmp"}
if payload := h.result_payload(); len(payload) != 2 {
t.Fatalf("the shell must be typed into when the sync did not handle the move: %#v", payload)
}
h.sync_handled = true
payload := h.result_payload()
if payload["sync"] != "1" || payload["path"] != "/tmp" {
t.Fatalf("unexpected payload: %#v", payload)
}
}
-1
View File
@@ -1 +0,0 @@
# License: GPLv3 Copyright: 2026, FWS
-47
View File
@@ -1,47 +0,0 @@
#!/usr/bin/env python
# License: GPLv3 Copyright: 2026, FWS
# The keybindings live in the Python options object, while the searchable list
# UI lives in the Go command palette. Collect the data here, then replace this
# process with the palette reading the same terminal, so the panel can run in a
# dock without a second protocol between the two.
import json
import os
import sys
import tempfile
from contextlib import suppress
help_text = 'Browse all keyboard shortcuts in a searchable panel'
usage = ''
OPTIONS = r"""
""".format
def main(args: list[str]) -> None:
from kittens.command_palette.main import collect_keys_data
from kitty.config import load_config
from kitty.constants import config_dir, kitten_exe
conf = os.path.join(config_dir, 'kitty.conf')
opts = load_config(conf) if os.path.exists(conf) else load_config()
fd, path = tempfile.mkstemp(prefix='kitty-shortcuts-', suffix='.json')
try:
with os.fdopen(fd, 'w', encoding='utf-8') as f:
json.dump(collect_keys_data(opts), f)
exe = kitten_exe()
os.execv(exe, [exe, 'command-palette', '--data-file=' + path, '--read-only'])
finally:
# execv only returns on failure; on success the Go side removes the file.
with suppress(OSError):
os.unlink(path)
if __name__ == '__main__':
main(sys.argv)
elif __name__ == '__doc__':
cd = sys.cli_docs # type: ignore
cd['usage'] = usage
cd['options'] = OPTIONS
cd['help_text'] = help_text
cd['short_desc'] = 'Browse all keyboard shortcuts in a searchable panel'
-18
View File
@@ -66,24 +66,6 @@ func rune_to_index_map(alphabet string) *map[rune]int {
return &runeToIndexMap return &runeToIndexMap
} }
// next_selection moves pos by delta positions in a list of marks choices,
// wrapping around, as the arrow keys do in the list picker. A negative pos,
// meaning nothing is selected yet, selects the first choice when moving down
// and the last one when moving up, and a stale pos falls back to the first
// choice so that the arrow keys never stop working.
func next_selection(pos, marks, delta int) int {
if marks < 1 {
return -1
}
if pos < 0 || pos >= marks {
if delta < 0 {
return marks - 1
}
return 0
}
return ((pos+delta)%marks + marks) % marks
}
// decode_hint converts a hint to its corresponding index as it would appear in // decode_hint converts a hint to its corresponding index as it would appear in
// the breadth-first traversal of the prefix tree generated by the given // the breadth-first traversal of the prefix tree generated by the given
// alphabet. // alphabet.
+24 -110
View File
@@ -7,7 +7,6 @@ import (
"fmt" "fmt"
"io" "io"
"os" "os"
"sort"
"strconv" "strconv"
"strings" "strings"
"unicode" "unicode"
@@ -161,10 +160,6 @@ func main(_ *cli.Command, o *Options, args []string) (rc int, err error) {
} }
} }
chosen := []*Mark{} chosen := []*Mark{}
// The list navigation is only offered when the input is an ordered list of
// choices, see the --pick-from-list option.
pick_from_list := o.PickFromList
selected_mark := -1
lp, err := loop.New(loop.NoAlternateScreen) // no alternate screen reduces flicker on exit lp, err := loop.New(loop.NoAlternateScreen) // no alternate screen reduces flicker on exit
if err != nil { if err != nil {
return return
@@ -173,9 +168,8 @@ func main(_ *cli.Command, o *Options, args []string) (rc int, err error) {
faint := fctx.SprintFunc("dim") faint := fctx.SprintFunc("dim")
hint_style := fctx.SprintFunc(fmt.Sprintf("fg=%s bg=%s bold", o.HintsForegroundColor, o.HintsBackgroundColor)) hint_style := fctx.SprintFunc(fmt.Sprintf("fg=%s bg=%s bold", o.HintsForegroundColor, o.HintsBackgroundColor))
text_style := fctx.SprintFunc(fmt.Sprintf("fg=%s bg=%s bold", o.HintsTextColor, o.HintsTextBackgroundColor)) text_style := fctx.SprintFunc(fmt.Sprintf("fg=%s bg=%s bold", o.HintsTextColor, o.HintsTextBackgroundColor))
selected_style := fctx.SprintFunc("reverse")
highlight_mark := func(m *Mark, mark_text string, selected bool) string { highlight_mark := func(m *Mark, mark_text string) string {
hint := encode_hint(m.Index, alphabet) hint := encode_hint(m.Index, alphabet)
if current_input != "" && !strings.HasPrefix(hint, current_input) { if current_input != "" && !strings.HasPrefix(hint, current_input) {
return faint(mark_text) return faint(mark_text)
@@ -213,9 +207,6 @@ func main(_ *cli.Command, o *Options, args []string) (rc int, err error) {
mark_text = string(runes[hint_runes:]) mark_text = string(runes[hint_runes:])
} }
ans := hint_style(hint) + text_style(mark_text) ans := hint_style(hint) + text_style(mark_text)
if selected {
ans = selected_style(ans)
}
return fmt.Sprintf("\x1b]8;;mark:%d\a%s\x1b]8;;\a", m.Index, ans) return fmt.Sprintf("\x1b]8;;mark:%d\a%s\x1b]8;;\a", m.Index, ans)
} }
@@ -226,7 +217,7 @@ func main(_ *cli.Command, o *Options, args []string) (rc int, err error) {
if ignore_mark_indices.Has(mark.Index) { if ignore_mark_indices.Has(mark.Index) {
continue continue
} }
mtext := highlight_mark(mark, ans[mark.Start:mark.End], pick_from_list && mark.Index == selected_mark) mtext := highlight_mark(mark, ans[mark.Start:mark.End])
ans = ans[:mark.Start] + mtext + ans[mark.End:] ans = ans[:mark.Start] + mtext + ans[mark.End:]
} }
ans = strings.ReplaceAll(ans, "\x00", "") ans = strings.ReplaceAll(ans, "\x00", "")
@@ -247,75 +238,6 @@ func main(_ *cli.Command, o *Options, args []string) (rc int, err error) {
current_text = "" current_text = ""
} }
// The marks in the order they were given, which is the order of the list
// the user sees rather than the order of the hints
ordered_indices := make([]int, 0, len(index_map))
for idx := range index_map {
ordered_indices = append(ordered_indices, idx)
}
sort.Ints(ordered_indices)
visible_marks := func() []*Mark {
ans := make([]*Mark, 0, len(ordered_indices))
for _, idx := range ordered_indices {
m := index_map[idx]
if m == nil || ignore_mark_indices.Has(m.Index) {
continue
}
if current_input != "" && !strings.HasPrefix(encode_hint(idx, alphabet), current_input) {
continue
}
ans = append(ans, m)
}
return ans
}
select_first := func() {
selected_mark = -1
if marks := visible_marks(); len(marks) > 0 {
selected_mark = marks[0].Index
}
}
choose_index := func(idx int) {
m := index_map[idx]
if m == nil {
current_input = ""
current_text = ""
draw_screen()
return
}
chosen = append(chosen, m)
ignore_mark_indices.Add(m.Index)
if o.Multiple {
reset()
select_first()
draw_screen()
} else {
lp.Quit(0)
}
}
select_by := func(delta int) {
marks := visible_marks()
if len(marks) == 0 {
return
}
pos := -1
for i, m := range marks {
if m.Index == selected_mark {
pos = i
break
}
}
if pos < 0 {
pos = 0
}
pos = next_selection(pos, len(marks), delta)
selected_mark = marks[pos].Index
current_text = ""
draw_screen()
}
if pick_from_list {
select_first()
}
lp.OnInitialize = func() (string, error) { lp.OnInitialize = func() (string, error) {
lp.SetCursorVisible(false) lp.SetCursorVisible(false)
lp.SetWindowTitle(window_title) lp.SetWindowTitle(window_title)
@@ -373,15 +295,13 @@ func main(_ *cli.Command, o *Options, args []string) (rc int, err error) {
} }
if len(matches) == 1 { if len(matches) == 1 {
chosen = append(chosen, matches[0]) chosen = append(chosen, matches[0])
ignore_mark_indices.Add(matches[0].Index) if o.Multiple {
if !o.Multiple { ignore_mark_indices.Add(matches[0].Index)
reset()
} else {
lp.Quit(0) lp.Quit(0)
return nil return nil
} }
reset()
}
if pick_from_list {
select_first()
} }
current_text = "" current_text = ""
draw_screen() draw_screen()
@@ -390,14 +310,7 @@ func main(_ *cli.Command, o *Options, args []string) (rc int, err error) {
} }
lp.OnKeyEvent = func(ev *loop.KeyEvent) error { lp.OnKeyEvent = func(ev *loop.KeyEvent) error {
if pick_from_list && (ev.MatchesPressOrRepeat("up") || ev.MatchesPressOrRepeat("down")) { if ev.MatchesPressOrRepeat("backspace") {
ev.Handled = true
if ev.MatchesPressOrRepeat("up") {
select_by(-1)
} else {
select_by(1)
}
} else if ev.MatchesPressOrRepeat("backspace") {
ev.Handled = true ev.Handled = true
r := []rune(current_input) r := []rune(current_input)
if len(r) > 0 { if len(r) > 0 {
@@ -405,25 +318,26 @@ func main(_ *cli.Command, o *Options, args []string) (rc int, err error) {
current_input = string(r) current_input = string(r)
current_text = "" current_text = ""
} }
if pick_from_list {
select_first()
}
draw_screen() draw_screen()
} else if ev.MatchesPressOrRepeat("enter") { } else if ev.MatchesPressOrRepeat("enter") || ev.MatchesPressOrRepeat("space") {
ev.Handled = true ev.Handled = true
if pick_from_list { if current_input != "" {
if selected_mark > -1 { char_to_index := rune_to_index_map(alphabet)
choose_index(selected_mark) idx := decode_hint(current_input, char_to_index)
} else if marks := visible_marks(); len(marks) > 0 { if m := index_map[idx]; m != nil {
choose_index(marks[0].Index) chosen = append(chosen, m)
ignore_mark_indices.Add(idx)
if o.Multiple {
reset()
draw_screen()
} else {
lp.Quit(0)
}
} else {
current_input = ""
current_text = ""
draw_screen()
} }
} else if current_input != "" {
choose_index(decode_hint(current_input, rune_to_index_map(alphabet)))
}
} else if ev.MatchesPressOrRepeat("space") {
ev.Handled = true
if !pick_from_list && current_input != "" {
choose_index(decode_hint(current_input, rune_to_index_map(alphabet)))
} }
} else if ev.MatchesPressOrRepeat("esc") { } else if ev.MatchesPressOrRepeat("esc") {
if o.Multiple { if o.Multiple {
-8
View File
@@ -271,14 +271,6 @@ elsewhere. See {hints_url} for details.
--window-title --window-title
The title for the hints window, default title is based on the type of text being The title for the hints window, default title is based on the type of text being
hinted. hinted.
--pick-from-list
type=bool-set
The input is an ordered list of choices rather than text to search, as used by the
clipboard history picker. The first choice is selected and the arrow keys move the
selection, so a choice can be picked with :kbd:`Enter` instead of typing the
letters of its hint.
""".format( """.format(
default_regex=DEFAULT_REGEX, default_regex=DEFAULT_REGEX,
line='{{line}}', line='{{line}}',
-33
View File
@@ -1,33 +0,0 @@
// License: GPLv3 Copyright: 2026, Kovid Goyal, <kovid at kovidgoyal.net>
package hints
import "testing"
func TestNextSelection(t *testing.T) {
cases := []struct {
pos, marks, delta, expected int
}{
// Nothing selected yet: down selects the first choice, up the last one
{-1, 3, 0, 0},
{-1, 3, 1, 0},
{-1, 3, -1, 2},
// Moving past either end wraps around
{0, 3, 1, 1},
{2, 3, 1, 0},
{0, 3, -1, 2},
{1, 1, 2, 0},
{0, 3, 4, 1},
{0, 3, -4, 2},
// A stale position falls back to the first choice
{5, 3, 1, 0},
// An empty list has nothing to select
{-1, 0, 1, -1},
{0, 0, -1, -1},
}
for _, c := range cases {
if got := next_selection(c.pos, c.marks, c.delta); got != c.expected {
t.Fatalf("next_selection(%d, %d, %d) = %d, expected %d", c.pos, c.marks, c.delta, got, c.expected)
}
}
}
-95
View File
@@ -40,7 +40,6 @@ from .clipboard import (
set_clipboard_string, set_clipboard_string,
set_primary_selection, set_primary_selection,
) )
from .clipboard_history import ClipboardHistory
from .colors import ColorSchemes, theme_colors from .colors import ColorSchemes, theme_colors
from .conf.utils import BadLine, KeyAction, to_cmdline from .conf.utils import BadLine, KeyAction, to_cmdline
from .config import common_opts_as_dict, prepare_config_file_for_editing, store_effective_config from .config import common_opts_as_dict, prepare_config_file_for_editing, store_effective_config
@@ -420,7 +419,6 @@ class Boss:
self.atexit = Atexit() self.atexit = Atexit()
set_layout_options(opts) set_layout_options(opts)
self.clipboard = Clipboard() self.clipboard = Clipboard()
self.clipboard_history = ClipboardHistory()
self.window_for_dispatch: Window | None = None self.window_for_dispatch: Window | None = None
self.primary_selection = Clipboard(ClipboardType.primary_selection) self.primary_selection = Clipboard(ClipboardType.primary_selection)
self.update_check_started = False self.update_check_started = False
@@ -2530,7 +2528,6 @@ class Boss:
if not self._call_on_quit_watchers({'confirmed': True}): if not self._call_on_quit_watchers({'confirmed': True}):
set_application_quit_request(NO_CLOSE_REQUESTED) set_application_quit_request(NO_CLOSE_REQUESTED)
return return
self.save_last_session()
self.save_session_if_logging_out() self.save_session_if_logging_out()
set_application_quit_request(IMPERATIVE_CLOSE_REQUESTED) set_application_quit_request(IMPERATIVE_CLOSE_REQUESTED)
return return
@@ -2560,20 +2557,9 @@ class Boss:
if not self._call_on_quit_watchers({'confirmed': True}): if not self._call_on_quit_watchers({'confirmed': True}):
set_application_quit_request(NO_CLOSE_REQUESTED) set_application_quit_request(NO_CLOSE_REQUESTED)
return return
self.save_last_session()
self.save_session_if_logging_out() self.save_session_if_logging_out()
set_application_quit_request(IMPERATIVE_CLOSE_REQUESTED if confirmed else NO_CLOSE_REQUESTED) set_application_quit_request(IMPERATIVE_CLOSE_REQUESTED if confirmed else NO_CLOSE_REQUESTED)
def save_last_session(self) -> None:
# Must run before the quit request is set: the C side then closes the windows and there is
# nothing left to serialize. Saving an empty session is a no-op, so this never clobbers a
# good state with a torn down one.
from .main import is_panel_kitten
from .session_restore import save_session_of
if not is_panel_kitten():
save_session_of(self)
def save_session_if_logging_out(self) -> None: def save_session_if_logging_out(self) -> None:
from .logout_session import is_logout_in_progress from .logout_session import is_logout_in_progress
@@ -2856,15 +2842,6 @@ class Boss:
data = collect_keys_data(get_options()) data = collect_keys_data(get_options())
self.run_kitten_with_metadata('command-palette', input_data=json.dumps(data), window=self.window_for_dispatch) self.run_kitten_with_metadata('command-palette', input_data=json.dumps(data), window=self.window_for_dispatch)
def show_leader_keymap(self, prefix: Any, definitions: Any = None) -> None:
"""Show the keys available under the leader prefix in the palette overlay."""
from kittens.command_palette.main import collect_leader_data
data = collect_leader_data(get_options(), prefix, definitions)
if not data['leader']['bindings']:
return
self.run_kitten_with_metadata('command-palette', input_data=json.dumps(data), window=self.window_for_dispatch)
@ac( @ac(
'tab', 'tab',
""" """
@@ -3182,68 +3159,6 @@ class Boss:
if text: if text:
w.paste_with_actions(text) w.paste_with_actions(text)
def _clipboard_history_preview(self, text: str) -> str:
# The picker shows one line per entry, so flatten newlines and keep the line short
q = ' '.join(text.split())
return q if len(q) <= 120 else q[:117] + '…'
def _clipboard_history_label(self, text: str, copied_at: float) -> str:
# The time an entry was copied tells apart entries that look alike
from datetime import datetime
when = datetime.fromtimestamp(copied_at).strftime('%H:%M')
return f'{when} {self._clipboard_history_preview(text) or _("(blank)")}'
def _clipboard_history_target_title(self, target: Window | None) -> str:
title = '' if target is None else ' '.join(target.title.split())
if not title:
return _('unknown window')
return title if len(title) <= 80 else title[:77] + '…'
def _choose_from_clipboard_history(self, entries: tuple[tuple[str, float], ...]) -> None:
if not entries:
self.ring_bell_if_allowed()
return
previews = [(text, self._clipboard_history_label(text, when)) for text, when in entries]
# The picker is itself the active window while it is open, so keep the window the user was
# working in to paste into once it closes. The window can be gone by then.
target = self.window_for_dispatch or self.active_window
def chosen(text: str | None) -> None:
if text and target is not None:
w = self.window_id_map.get(target.id)
if w is not None:
w.paste_with_actions(text)
self.choose_entry(
_('Clipboard history'),
previews,
chosen,
subtitle=_('Paste into: {}').format(self._clipboard_history_target_title(target)),
footer=_('↑/↓ move · Enter paste · Esc cancel'),
hints_args=('--pick-from-list',),
)
@ac('cp', 'Paste an entry from the clipboard history. See :ref:`clipboard_history`.')
def paste_from_clipboard_history(self) -> None:
self._choose_from_clipboard_history(self.clipboard_history.entries_with_times())
@ac('cp', 'Search the clipboard history and paste the selected entry. See :ref:`clipboard_history`.')
def search_clipboard_history(self) -> None:
if not self.clipboard_history:
self.ring_bell_if_allowed()
return
def query_entered(query: str) -> None:
self._choose_from_clipboard_history(self.clipboard_history.search_with_times(query))
self.get_line(
_('Search the clipboard history. Leave empty to list everything.'),
query_entered,
prompt=_('Search: '),
window_title=_('Search clipboard history'),
)
def current_primary_selection(self) -> str: def current_primary_selection(self) -> str:
return get_primary_selection() if supports_primary_selection else '' return get_primary_selection() if supports_primary_selection else ''
@@ -3999,7 +3914,6 @@ class Boss:
callback: Callable[[_T | str | None], None], callback: Callable[[_T | str | None], None],
subtitle: str = '', subtitle: str = '',
hints_args: tuple[str, ...] | None = None, hints_args: tuple[str, ...] | None = None,
footer: str = '',
) -> Window | None: ) -> Window | None:
lines = [title, subtitle, ' '] if subtitle else [title, ' '] lines = [title, subtitle, ' '] if subtitle else [title, ' ']
idx_map: list[_T | str | None] = [] idx_map: list[_T | str | None] = []
@@ -4012,8 +3926,6 @@ class Boss:
lines.append(text) lines.append(text)
else: else:
lines.append(fmt.format(len(idx_map), text)) lines.append(fmt.format(len(idx_map), text))
if footer:
lines.append(f' {footer}')
def done(data: dict[str, Any], target_window_id: int, self: Boss) -> None: def done(data: dict[str, Any], target_window_id: int, self: Boss) -> None:
nonlocal ans nonlocal ans
@@ -4035,13 +3947,6 @@ class Boss:
def goto_session(self, *cmdline: str) -> None: def goto_session(self, *cmdline: str) -> None:
goto_session(self, cmdline) goto_session(self, cmdline)
@ac('session', 'Restore the tabs and windows of the session saved when kitty last quit. See :ref:`sessions`.')
def restore_last_session(self) -> None:
from .session_restore import restore_last_session_into
if not restore_last_session_into(self):
self.ring_bell_if_allowed()
@ac('session', 'Save the current kitty state as a session file. See :ref:`save_as_session`.') @ac('session', 'Save the current kitty state as a session file. See :ref:`save_as_session`.')
def save_as_session(self, *cmdline: str) -> None: def save_as_session(self, *cmdline: str) -> None:
save_as_session(self, cmdline) save_as_session(self, cmdline)
-16
View File
@@ -3,7 +3,6 @@
import os import os
import sys import sys
import tempfile
import termios import termios
from collections import defaultdict from collections import defaultdict
from collections.abc import Callable, Generator, Iterable, Mapping, Sequence from collections.abc import Callable, Generator, Iterable, Mapping, Sequence
@@ -22,20 +21,6 @@ if TYPE_CHECKING:
from .window import CwdRequest from .window import CwdRequest
@run_once
def cwd_sync_dir() -> str:
"""Directory shared by every window of this instance for the file manager's
working directory sync. It is created with private permissions so that only
this user can read the paths the shells publish, and lives in the runtime
directory, which the login session already clears. An empty string means the
sync is unavailable and the participating kittens keep their own behaviour."""
base = os.environ.get('XDG_RUNTIME_DIR')
try:
return tempfile.mkdtemp(prefix='kitty-cwd-sync-', dir=base if base and os.path.isdir(base) else None)
except OSError:
return ''
if is_macos: if is_macos:
from kitty.fast_data_types import abspath_of_process as _abspath_of_process from kitty.fast_data_types import abspath_of_process as _abspath_of_process
from kitty.fast_data_types import cmdline_of_process as cmdline_ from kitty.fast_data_types import cmdline_of_process as cmdline_
@@ -479,7 +464,6 @@ class Child:
elif opts.terminfo_type == 'direct': elif opts.terminfo_type == 'direct':
env['TERMINFO'] = base64_terminfo_data() env['TERMINFO'] = base64_terminfo_data()
env['KITTY_INSTALLATION_DIR'] = kitty_base_dir env['KITTY_INSTALLATION_DIR'] = kitty_base_dir
env['KITTY_CWD_SYNC_DIR'] = cwd_sync_dir()
self.unmodified_argv = list(self.argv) self.unmodified_argv = list(self.argv)
if not self.should_run_via_run_shell_kitten and 'disabled' not in opts.shell_integration: if not self.should_run_via_run_shell_kitten and 'disabled' not in opts.shell_integration:
from .shell_integration import modify_shell_environ from .shell_integration import modify_shell_environ
+4 -24
View File
@@ -9,7 +9,6 @@ from gettext import gettext as _
from tempfile import TemporaryFile from tempfile import TemporaryFile
from typing import IO, NamedTuple, Union from typing import IO, NamedTuple, Union
from .clipboard_history import text_from_mime_data
from .conf.utils import uniq from .conf.utils import uniq
from .constants import supports_primary_selection from .constants import supports_primary_selection
from .fast_data_types import ( from .fast_data_types import (
@@ -97,33 +96,15 @@ class Clipboard:
self.clipboard_type = clipboard_type self.clipboard_type = clipboard_type
self.enabled = self.clipboard_type is ClipboardType.clipboard or supports_primary_selection self.enabled = self.clipboard_type is ClipboardType.clipboard or supports_primary_selection
def set_text(self, x: str | bytes, private: bool = False) -> None: def set_text(self, x: str | bytes) -> None:
if isinstance(x, str): if isinstance(x, str):
x = x.encode('utf-8') x = x.encode('utf-8')
self.set_mime({'text/plain': x}, private=private) self.set_mime({'text/plain': x})
def set_mime(self, data: Mapping[str, DataType], private: bool = False) -> None: def set_mime(self, data: Mapping[str, DataType]) -> None:
if self.enabled and isinstance(data, dict): if self.enabled and isinstance(data, dict):
self.data = dict(data) self.data = dict(data)
set_clipboard_data_types(self.clipboard_type, tuple(self.data)) set_clipboard_data_types(self.clipboard_type, tuple(self.data))
self._record_in_history(private=private)
def _record_in_history(self, private: bool) -> None:
# Only plain text is useful in the history, and only for the clipboard: the primary selection
# changes constantly and would evict everything else. Private writes are dropped by the
# history itself, so that secrets never reach it.
if self.clipboard_type is not ClipboardType.clipboard:
return
if 'text/plain' not in self.data:
return
try:
# The payload can be a chunker rather than bytes, as writes are streamed from a temp file
text = text_from_mime_data(self.data['text/plain'])
history = getattr(get_boss(), 'clipboard_history', None)
except Exception:
return
if text and history is not None:
history.add(text, private=private)
def get_text(self) -> str: def get_text(self) -> str:
parts: list[bytes] = [] parts: list[bytes] = []
@@ -328,8 +309,7 @@ class WriteRequest:
if pos is not None: if pos is not None:
self.mime_map[alias] = pos self.mime_map[alias] = pos
x = {mime: self.tempfile.create_chunker(pos.start, pos.size) for mime, pos in self.mime_map.items()} x = {mime: self.tempfile.create_chunker(pos.start, pos.size) for mime, pos in self.mime_map.items()}
# A write request that carries a password is private: never keep its data in the history cp.set_mime(x)
cp.set_mime(x, private=bool(self.password))
def abort(self, msg: str) -> ValueError: def abort(self, msg: str) -> ValueError:
# returns the error to raise, so that callers read as: raise self.abort(...) # returns the error to raise, so that callers read as: raise self.abort(...)
-139
View File
@@ -1,139 +0,0 @@
#!/usr/bin/env python
# License: GPL v3 Copyright: 2026, Kovid Goyal <kovid at kovidgoyal.net>
# A bounded, in-memory history of what was copied to the clipboard.
#
# Nothing is ever written to disk: copied text often contains secrets and the history is meant to
# help within one kitty instance, not to outlive it. Entries marked private are never recorded.
from collections import deque
from time import time
from typing import Iterator
DEFAULT_MAX_ENTRIES = 50
MAX_ENTRY_CHARS = 64 * 1024
MAX_TOTAL_CHARS = 1024 * 1024
def text_from_mime_data(data: object, max_chars: int = MAX_ENTRY_CHARS) -> str:
"""Extract text from a clipboard MIME payload, or an empty string when it is not text.
Clipboard payloads are either raw bytes or a factory returning a chunker, as the data can be
streamed from a temporary file. Only the start of the payload is materialized, since an entry
longer than max_chars is not kept anyway.
"""
limit = 4 * max_chars # a UTF-8 character takes at most four bytes
if isinstance(data, bytes | bytearray | memoryview):
raw = bytes(data[:limit])
elif callable(data):
chunks: list[bytes] = []
size = 0
chunker = data()
while True:
q = chunker()
if not q:
break
chunks.append(q)
size += len(q)
if size >= limit:
break
raw = b''.join(chunks)[:limit]
else:
return ''
return raw.decode('utf-8', 'replace')
def match_score(needle: str, haystack: str) -> int:
"""Return a score, lower is better, or -1 when haystack does not contain needle as a subsequence.
A plain substring match always scores better than a subsequence so that what the user typed as
a contiguous string is ranked first, which is what people expect from a fuzzy filter.
"""
if not needle:
return 0
needle, haystack = needle.lower(), haystack.lower()
pos = haystack.find(needle)
if pos > -1:
return pos
gaps = 0
start = 0
for ch in needle:
idx = haystack.find(ch, start)
if idx < 0:
return -1
gaps += idx - start
start = idx + 1
return MAX_TOTAL_CHARS + gaps
class ClipboardHistory:
def __init__(
self,
max_entries: int = DEFAULT_MAX_ENTRIES,
max_entry_chars: int = MAX_ENTRY_CHARS,
max_total_chars: int = MAX_TOTAL_CHARS,
) -> None:
self.max_entries = max(1, max_entries)
self.max_entry_chars = max(1, max_entry_chars)
self.max_total_chars = max(1, max_total_chars)
self._entries: deque[tuple[str, float]] = deque()
self._total_chars = 0
def __len__(self) -> int:
return len(self._entries)
def __bool__(self) -> bool:
return bool(self._entries)
def __iter__(self) -> Iterator[str]:
return iter(self.entries())
def __getitem__(self, idx: int) -> str:
return self.entries()[idx]
def entries(self) -> tuple[str, ...]:
"""All entries, most recently copied first."""
return tuple(text for text, _ in reversed(self._entries))
def entries_with_times(self) -> tuple[tuple[str, float], ...]:
"""All entries with the time they were copied, most recent first."""
return tuple(reversed(self._entries))
def clear(self) -> None:
self._entries.clear()
self._total_chars = 0
def add(self, text: str, private: bool = False, timestamp: float | None = None) -> bool:
"""Record text, returning False when it is deliberately not recorded."""
if private or not text or not text.strip():
return False
if len(text) > self.max_entry_chars:
return False
# A repeated copy moves the entry to the top instead of duplicating it
for idx, (old_text, _) in enumerate(self._entries):
if old_text == text:
del self._entries[idx]
self._total_chars -= len(old_text)
break
self._entries.append((text, time() if timestamp is None else timestamp))
self._total_chars += len(text)
while self._entries and (len(self._entries) > self.max_entries or self._total_chars > self.max_total_chars):
self._total_chars -= len(self._entries.popleft()[0])
return True
def search(self, query: str) -> tuple[str, ...]:
"""Entries matching query, best match first, newest first among equal scores."""
return tuple(text for text, _ in self.search_with_times(query))
def search_with_times(self, query: str) -> tuple[tuple[str, float], ...]:
"""The entries search() returns, with the time each one was copied."""
entries = self.entries_with_times()
if not query.strip():
return entries
scored = []
for idx, (text, when) in enumerate(entries):
score = match_score(query, text)
if score > -1:
scored.append((score, idx, text, when))
scored.sort(key=lambda x: (x[0], x[1]))
return tuple((text, when) for _, _, text, when in scored)
+4 -4
View File
@@ -86,7 +86,7 @@ def generate_class(defn: Definition, loc: str) -> tuple[str, str]:
if isinstance(option, MultiOption): if isinstance(option, MultiOption):
mval: dict[str, dict[str, Any]] = {'macos': {}, 'linux': {}, '': {}} mval: dict[str, dict[str, Any]] = {'macos': {}, 'linux': {}, '': {}}
func, typ = option_type_data(option) func, typ = option_type_data(option)
assert callable(func), getattr(func, '__name__', func) assert isinstance(func, types.FunctionType)
for val in option: for val in option:
if val.add_to_default: if val.add_to_default:
gr = mval[val.only] gr = mval[val.only]
@@ -115,7 +115,7 @@ def generate_class(defn: Definition, loc: str) -> tuple[str, str]:
func = str func = str
elif defn.has_color_table and option.is_color_table_color: elif defn.has_color_table and option.is_color_table_color:
func, typ = option_type_data(option) func, typ = option_type_data(option)
assert callable(func), getattr(func, '__name__', func) assert isinstance(func, types.FunctionType)
t(f' ans[{option.name!r}] = {func.__name__}(val)') t(f' ans[{option.name!r}] = {func.__name__}(val)')
tc_imports.add((func.__module__, func.__name__)) tc_imports.add((func.__module__, func.__name__))
cnum = int(option.name[5:]) cnum = int(option.name[5:])
@@ -130,7 +130,7 @@ def generate_class(defn: Definition, loc: str) -> tuple[str, str]:
params = dict(inspect.signature(func).parameters) params = dict(inspect.signature(func).parameters)
except Exception: except Exception:
params = {} params = {}
assert callable(func), getattr(func, '__name__', func) assert isinstance(func, types.FunctionType)
if 'dict_with_parse_results' in params: if 'dict_with_parse_results' in params:
t(f' {func.__name__}(val, ans)') t(f' {func.__name__}(val, ans)')
else: else:
@@ -188,7 +188,7 @@ def generate_class(defn: Definition, loc: str) -> tuple[str, str]:
for aname, action in defn.actions.items(): for aname, action in defn.actions.items():
option_names.add(aname) option_names.add(aname)
action_parsers[aname] = func = action.parser_func action_parsers[aname] = func = action.parser_func
assert callable(func), getattr(func, '__name__', func) assert isinstance(func, types.FunctionType)
th = get_type_hints(func) th = get_type_hints(func)
rettype = th['return'] rettype = th['return']
typ = option_type_as_str(rettype) typ = option_type_as_str(rettype)
-40
View File
@@ -80,45 +80,6 @@ def prepare_config_file_for_editing() -> str:
return defconf return defconf
def finalize_leader(opts: Options) -> None:
"""Validate the leader shortcut once so that key handling can use it directly."""
from .keys import leader_key_from_options
try:
opts.leader_key = leader_key_from_options(opts)
except Exception as err:
opts.leader_key = None
log_error(f'Ignoring invalid leader shortcut: {opts.leader}. Error: {err}')
def append_map_to_config(key: str, definition: str, conf_path: str = '') -> str:
"""Append a map directive to the user config, creating it when needed.
The path is returned so that callers can report it. Only the mapping is
written, existing configuration is never rewritten.
"""
from .constants import config_dir
path = conf_path or os.path.join(config_dir, 'kitty.conf')
parent = os.path.dirname(path)
if parent:
with suppress(FileExistsError):
os.makedirs(parent)
needs_newline = False
try:
if os.path.getsize(path) > 0:
with open(path, 'rb') as f:
f.seek(-1, os.SEEK_END)
needs_newline = f.read(1) != b'\n'
except FileNotFoundError:
pass
with open(path, 'ab') as f:
if needs_newline:
f.write(b'\n')
f.write(f'map {key} {definition}\n'.encode('utf-8'))
return path
def finalize_keys(opts: Options, accumulate_bad_lines: list[BadLine] | None = None) -> None: def finalize_keys(opts: Options, accumulate_bad_lines: list[BadLine] | None = None) -> None:
defns: list[KeyDefinition] = [] defns: list[KeyDefinition] = []
for d in opts.map: for d in opts.map:
@@ -157,7 +118,6 @@ def finalize_keys(opts: Options, accumulate_bad_lines: list[BadLine] | None = No
items = m.keymap[defn.trigger] = [kd for kd in items if defn.rest != kd.rest or defn.options.when_focus_on != kd.options.when_focus_on] items = m.keymap[defn.trigger] = [kd for kd in items if defn.rest != kd.rest or defn.options.when_focus_on != kd.options.when_focus_on]
items.append(defn) items.append(defn)
opts.keyboard_modes = modes opts.keyboard_modes = modes
finalize_leader(opts)
def finalize_mouse_mappings(opts: Options, accumulate_bad_lines: list[BadLine] | None = None) -> None: def finalize_mouse_mappings(opts: Options, accumulate_bad_lines: list[BadLine] | None = None) -> None:
+1 -32
View File
@@ -23,7 +23,7 @@ from .fast_data_types import (
set_ignore_os_keyboard_processing, set_ignore_os_keyboard_processing,
) )
from .options.types import Options from .options.types import Options
from .options.utils import KeyboardMode, KeyDefinition, KeyFallbackType, KeyMap, KeyMapOptions, parse_shortcut from .options.utils import KeyboardMode, KeyDefinition, KeyFallbackType, KeyMap, KeyMapOptions
from .typing_compat import ScreenType from .typing_compat import ScreenType
if TYPE_CHECKING: if TYPE_CHECKING:
@@ -40,14 +40,6 @@ def keyboard_mode_name(screen: ScreenType) -> str:
return 'application' if screen.cursor_key_mode else 'normal' return 'application' if screen.cursor_key_mode else 'normal'
def leader_key_from_options(opts: Options) -> SingleKey | None:
"""The shortcut that opens the leader tree, or None when disabled."""
raw = (getattr(opts, 'leader', '') or '').strip()
if not raw or raw.lower() in ('none', 'no', 'off'):
return None
return parse_shortcut(raw)
def get_shortcut(keymap: KeyMap, ev: KeyEvent) -> list[KeyDefinition] | None: def get_shortcut(keymap: KeyMap, ev: KeyEvent) -> list[KeyDefinition] | None:
mods = ev.mods & mod_mask mods = ev.mods & mod_mask
ans = keymap.get(SingleKey(mods, False, ev.key)) ans = keymap.get(SingleKey(mods, False, ev.key))
@@ -119,24 +111,6 @@ class Mappings:
self.keyboard_modes[''].keymap = km = km.copy() self.keyboard_modes[''].keymap = km = km.copy()
for sc in self.global_shortcuts.values(): for sc in self.global_shortcuts.values():
km.pop(sc, None) km.pop(sc, None)
self.leader_key: SingleKey | None = getattr(self.get_options(), 'leader_key', None)
if self.leader_key is None:
try:
self.leader_key = leader_key_from_options(self.get_options())
except Exception:
# An invalid leader is reported when the config is loaded.
self.leader_key = None
def leader_continuations(self, mode: KeyboardMode) -> list[KeyDefinition]:
"""Multi-key mappings whose first key is the leader key."""
ans: list[KeyDefinition] = []
if self.leader_key is None:
return ans
for defns in mode.keymap.values():
for d in defns:
if d.is_sequence and d.trigger == self.leader_key:
ans.append(d)
return ans
def clear_keyboard_modes(self) -> None: def clear_keyboard_modes(self) -> None:
had_mode = bool(self.keyboard_mode_stack) had_mode = bool(self.keyboard_mode_stack)
@@ -238,11 +212,6 @@ class Mappings:
# Handles shortcuts, return True if the key was consumed # Handles shortcuts, return True if the key was consumed
is_root_mode = not self.keyboard_mode_stack is_root_mode = not self.keyboard_mode_stack
mode = self.keyboard_modes[''] if is_root_mode else self.keyboard_mode_stack[-1] mode = self.keyboard_modes[''] if is_root_mode else self.keyboard_mode_stack[-1]
if is_root_mode and self.leader_key is not None and shortcut_matches(self.leader_key, ev):
continuations = self.matching_key_actions(self.leader_continuations(mode))
if continuations:
get_boss().show_leader_keymap(self.leader_key, continuations)
return True
key_action = get_shortcut(mode.keymap, ev) key_action = get_shortcut(mode.keymap, ev)
if key_action is None and self.global_shortcuts_map and (global_key_action := get_shortcut(self.global_shortcuts_map, ev)) is not None: if key_action is None and self.global_shortcuts_map and (global_key_action := get_shortcut(self.global_shortcuts_map, ev)) is not None:
if grab_keyboard(None): if grab_keyboard(None):
-2
View File
@@ -424,10 +424,8 @@ handle_fast_commandline(CLISpec *cli_spec, const char *instance_group_prefix) {
if (get_bool_cli_val(cli_spec, "version")) { if (get_bool_cli_val(cli_spec, "version")) {
if (isatty(STDOUT_FILENO)) { if (isatty(STDOUT_FILENO)) {
printf("\x1b[3mkitty\x1b[23m \x1b[32m%s\x1b[39m created by \x1b[1;34mKovid Goyal\x1b[22;39m\n", KITTY_VERSION); printf("\x1b[3mkitty\x1b[23m \x1b[32m%s\x1b[39m created by \x1b[1;34mKovid Goyal\x1b[22;39m\n", KITTY_VERSION);
printf("\x1b[3mfws-kitty\x1b[23m \x1b[32m0.1.17\x1b[39m by \x1b[1;34mBlackAngelTV\x1b[22;39m\n");
} else { } else {
printf("kitty %s created by Kovid Goyal\n", KITTY_VERSION); printf("kitty %s created by Kovid Goyal\n", KITTY_VERSION);
printf("fws-kitty 0.1.17 by BlackAngelTV\n");
} }
exit(0); exit(0);
} }
-3
View File
@@ -68,7 +68,6 @@ from .options.types import Options
from .options.utils import DELETE_ENV_VAR from .options.utils import DELETE_ENV_VAR
from .os_window_size import edge_spacing, initial_window_size_func from .os_window_size import edge_spacing, initial_window_size_func
from .session import create_sessions, get_os_window_sizing_data from .session import create_sessions, get_os_window_sizing_data
from .session_restore import save_session_of
from .shaders.slang import load_shader_programs from .shaders.slang import load_shader_programs
from .types import LayerShellConfig from .types import LayerShellConfig
from .utils import ( from .utils import (
@@ -395,8 +394,6 @@ def _run_app(opts: Options, args: CLIOptions, bad_lines: Sequence[BadLine] = (),
try: try:
boss.child_monitor.main_loop() boss.child_monitor.main_loop()
finally: finally:
if not _is_panel_kitten:
save_session_of(boss)
boss.destroy() boss.destroy()
+1 -19
View File
@@ -2,7 +2,7 @@
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net> # License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
import re import re
from collections.abc import Callable, Generator, Iterable, Mapping, Sequence from collections.abc import Callable, Generator, Iterable, Sequence
from re import Pattern from re import Pattern
from typing import Union from typing import Union
@@ -29,24 +29,6 @@ def marker_from_regex(expression: Union[str, 'Pattern[str]'], color: int, flags:
return marker return marker
def marker_from_spans(spans: Mapping[str, Sequence[tuple[int, int, int]]]) -> MarkerFunc:
"""A marker built from pre-computed spans, keyed by the text of their line.
Each span is (start, end, color), where color is a mark number. Marker
functions receive one line at a time without its number, hence the lookup
by text.
"""
def marker(text: str, left_address: int, right_address: int, color_address: int) -> Generator[None, None, None]:
for start, end, color in spans.get(text, ()):
set_uint_at_address(left_address, start)
set_uint_at_address(right_address, end - 1)
set_uint_at_address(color_address, max(1, min(color, 3)))
yield
return marker
def marker_from_multiple_regex(regexes: Iterable[tuple[int, str]], flags: int = re.UNICODE) -> MarkerFunc: def marker_from_multiple_regex(regexes: Iterable[tuple[int, str]], flags: int = re.UNICODE) -> MarkerFunc:
expr = '' expr = ''
color_map = {} color_map = {}
-68
View File
@@ -2183,73 +2183,6 @@ update_mock_pointer(PyObject *self UNUSED, PyObject *args) {
return Py_BuildValue("(iO)", result, updated ? Py_True : Py_False); return Py_BuildValue("(iO)", result, updated ? Py_True : Py_False);
} }
/* Hit test a point against two windows placed side by side in a mock tab, and
* return 1 or 2 for the window mouse_region() picks, or 0 when none is hit.
* A docked window must receive the clicks in its own area, whatever the edge it
* is docked at, so the edges are given here rather than assumed to be left. */
static PyObject *
mock_window_under_mouse(PyObject *self UNUSED, PyObject *args) {
PyObject *capsule;
int g[2][4];
int mouse_x, mouse_y;
if (!PyArg_ParseTuple(
args,
"O!iiiiiiiiii",
&PyCapsule_Type,
&capsule,
&g[0][0],
&g[0][1],
&g[0][2],
&g[0][3],
&g[1][0],
&g[1][1],
&g[1][2],
&g[1][3],
&mouse_x,
&mouse_y))
return NULL;
Window *w = PyCapsule_GetPointer(capsule, "Window");
if (!w) return NULL;
Screen *screen = w->render_data.screen;
if (!screen) return NULL;
OSWindow *saved_os_window = global_state.callback_os_window;
const id_type saved_hover = global_state.mouse_hover_in_window;
Window windows[2] = {*w, *w};
for (unsigned int i = 0; i < 2; i++) {
Window *win = windows + i;
win->id = w->id + i;
win->visible = true;
win->render_data.screen = screen;
win->render_data.geometry.left = (unsigned int)MAX(0, g[i][0]);
win->render_data.geometry.top = (unsigned int)MAX(0, g[i][1]);
win->render_data.geometry.right = (unsigned int)MAX(0, g[i][2]);
win->render_data.geometry.bottom = (unsigned int)MAX(0, g[i][3]);
zero_at_ptr(&win->padding);
zero_at_ptr(&win->size_mismatch_padding);
}
Tab tab = {.windows = windows, .num_windows = 2};
struct {
FONTS_DATA_HEAD
} fonts = {.logical_dpi_x = 72, .logical_dpi_y = 72, .fcm = {.cell_width = 10, .cell_height = 20}};
OSWindow osw = {
.tabs = &tab,
.num_tabs = 1,
.has_too_few_tabs = true,
.fonts_data = (FONTS_DATA_HANDLE)&fonts,
.viewport_width = 1400,
.viewport_height = 600,
.mouse_x = (double)mouse_x,
.mouse_y = (double)mouse_y};
global_state.callback_os_window = &osw;
global_state.mouse_hover_in_window = 0;
MouseRegion region = mouse_region(false, false);
unsigned long ans = region.window == windows ? 1 : region.window == windows + 1 ? 2 : 0;
global_state.callback_os_window = saved_os_window;
global_state.mouse_hover_in_window = saved_hover;
if (PyErr_Occurred()) return NULL;
return PyLong_FromUnsignedLong(ans);
}
static PyObject * static PyObject *
test_scale_scroll(PyObject *self UNUSED, PyObject *args) { test_scale_scroll(PyObject *self UNUSED, PyObject *args) {
PyObject *values; PyObject *values;
@@ -2325,7 +2258,6 @@ static PyMethodDef module_methods[] = {
METHODB(test_mapped_scroll_steps, METH_VARARGS), METHODB(test_mapped_scroll_steps, METH_VARARGS),
METHODB(send_mock_mouse_event_to_window, METH_VARARGS), METHODB(send_mock_mouse_event_to_window, METH_VARARGS),
METHODB(update_mock_pointer, METH_VARARGS), METHODB(update_mock_pointer, METH_VARARGS),
METHODB(mock_window_under_mouse, METH_VARARGS),
METHODB(send_mock_scroll_event_to_window, METH_VARARGS), METHODB(send_mock_scroll_event_to_window, METH_VARARGS),
METHODB(mock_mouse_selection, METH_VARARGS), METHODB(mock_mouse_selection, METH_VARARGS),
{NULL, NULL, 0, NULL} /* Sentinel */ {NULL, NULL, 0, NULL} /* Sentinel */
+1 -72
View File
@@ -2450,8 +2450,7 @@ lines is wrapped independently.
opt( opt(
'tab_title_template', 'tab_title_template',
'"{fmt.fg.red}{bell_symbol}{activity_symbol}{exit_status_symbol}{secure_input_symbol}' '"{fmt.fg.red}{bell_symbol}{activity_symbol}{exit_status_symbol}{secure_input_symbol}{fmt.fg.tab}{tab.last_focused_progress_percent}{title}"',
'{fmt.fg.tab}{tab.last_focused_progress_percent}{tab.active_wd_abbreviated} {title}"',
option_type='tab_title_template', option_type='tab_title_template',
long_text=""" long_text="""
A template to render the tab title. The default just renders the title with A template to render the tab title. The default just renders the title with
@@ -3791,22 +3790,6 @@ this option to alter all default shortcuts that use :opt:`kitty_mod`.
""", """,
) )
opt(
'leader',
'ctrl+space',
long_text="""
The key that opens the leader key tree. When you press it and there are
multi-key mappings starting with this key (for example
:code:`map ctrl+space>n new_os_window`), kitty displays every possible
continuation with its action and help text, without waiting for a timeout. See
:ref:`leader_keymap` for details.
Set it to :code:`none` to disable the leader key. Only mappings whose first key
is the leader key are affected, a leader key with no multi-key mapping behind it
is passed through to the program running in kitty.
""",
)
opt( opt(
'remap_modifiers', 'remap_modifiers',
'', '',
@@ -3976,15 +3959,6 @@ map(
'paste_from_selection shift+insert paste_from_selection', 'paste_from_selection shift+insert paste_from_selection',
) )
map(
'Paste from clipboard history',
'paste_from_clipboard_history --allow-fallback=shifted,ascii kitty_mod+alt+v paste_from_clipboard_history',
)
map(
'Search the clipboard history',
'search_clipboard_history --allow-fallback=shifted,ascii kitty_mod+alt+f search_clipboard_history',
)
map( map(
'Pass selection to program', 'Pass selection to program',
'pass_selection_to_program --allow-fallback=shifted,ascii kitty_mod+o pass_selection_to_program', 'pass_selection_to_program --allow-fallback=shifted,ascii kitty_mod+o pass_selection_to_program',
@@ -4157,22 +4131,6 @@ For more sophisticated control, such as using the current selection, use :ac:`re
map('Search the scrollback within a pager', 'search_scrollback --allow-fallback=shifted,ascii cmd+f search_scrollback', only='macos') map('Search the scrollback within a pager', 'search_scrollback --allow-fallback=shifted,ascii cmd+f search_scrollback', only='macos')
map(
'Search and highlight the scrollback in place',
'search_scrollback_prompt kitty_mod+alt+s search_scrollback_prompt',
long_text="""
Search the scrollback without opening a pager. Every match is highlighted in
the scrollback and the ``[current/total]`` counter is shown in the window title.
Prefix the query with ``\\c`` to match case sensitively and with ``\\r`` to use
a regular expression. While a search is active, :kbd:`n` and :kbd:`N` jump to
the next and previous match and :kbd:`Escape` ends the search. The default
binding is :kbd:`kitty_mod+alt+s` (:kbd:`Ctrl+Shift+Alt+S` by default).
The :ac:`scrollback_search_next`, :ac:`scrollback_search_prev` and
:ac:`clear_scrollback_search` actions can be mapped to other keys.
""",
)
egr() # }}} egr() # }}}
@@ -4694,23 +4652,6 @@ shortcuts. For a full description see :doc:`hints kitten </kittens/hints>`.
""") # }}} """) # }}}
# shortcuts.session {{{
agr('shortcuts.session', 'Sessions')
map(
'Restore the last session',
'restore_last_session --allow-fallback=shifted,ascii kitty_mod+alt+r restore_last_session',
long_text="""
Restores the tabs, windows, layouts and working directories of the session that
was saved when kitty last quit, without restarting kitty. The state is written
by :code:`quit`; see :ref:`sessions`. If there is nothing to restore, a bell is
rung instead.
""",
)
egr() # }}}
# shortcuts.misc {{{ # shortcuts.misc {{{
agr('shortcuts.misc', 'Miscellaneous') agr('shortcuts.misc', 'Miscellaneous')
@@ -4718,18 +4659,6 @@ map('Show documentation', 'show_kitty_doc kitty_mod+f1 show_kitty_doc overview')
map('Command palette', 'command_palette kitty_mod+f3 command_palette') map('Command palette', 'command_palette kitty_mod+f3 command_palette')
map(
'Keyboard shortcuts',
'keyboard_shortcuts kitty_mod+alt+h launch --type=window-dock --dock-edge=left --dock-size=60 kitty +kitten help',
long_text="""
Open the searchable keyboard shortcuts panel in a dock at the left edge of the
current window. It can also be launched manually with :code:`kitty +kitten help`.
The default binding is :kbd:`kitty_mod+alt+h` (:kbd:`Ctrl+Shift+Alt+H` by
default), so that :kbd:`kitty_mod+h` keeps browsing the scrollback in a pager
with :ac:`show_scrollback`.
""",
)
map( map(
'File manager', 'File manager',
'file_manager ctrl+shift+e launch --type=window-dock --dock-edge=left --dock-size=60 kitten file-manager', 'file_manager ctrl+shift+e launch --type=window-dock --dock-edge=left --dock-size=60 kitten file-manager',
-3
View File
@@ -1094,9 +1094,6 @@ class Parser:
def kitty_mod(self, val: str, ans: dict[str, typing.Any]) -> None: def kitty_mod(self, val: str, ans: dict[str, typing.Any]) -> None:
ans['kitty_mod'] = to_modifiers(val) ans['kitty_mod'] = to_modifiers(val)
def leader(self, val: str, ans: dict[str, typing.Any]) -> None:
ans['leader'] = str(val).strip()
def linux_bell_theme(self, val: str, ans: dict[str, typing.Any]) -> None: def linux_bell_theme(self, val: str, ans: dict[str, typing.Any]) -> None:
ans['linux_bell_theme'] = str(val) ans['linux_bell_theme'] = str(val)
-1
View File
@@ -4,7 +4,6 @@
#include "to-c.h" #include "to-c.h"
static void static void
convert_from_python_font_size(PyObject *val, Options *opts) { convert_from_python_font_size(PyObject *val, Options *opts) {
opts->font_size = PyFloat_AsDouble(val); opts->font_size = PyFloat_AsDouble(val);
+2 -14
View File
@@ -388,7 +388,6 @@ option_names = (
'italic_font', 'italic_font',
'kitten_alias', 'kitten_alias',
'kitty_mod', 'kitty_mod',
'leader',
'linux_bell_theme', 'linux_bell_theme',
'linux_display_server', 'linux_display_server',
'listen_on', 'listen_on',
@@ -614,7 +613,6 @@ class Options:
input_delay: int = 3 input_delay: int = 3
italic_font: FontSpec = FontSpec(family=None, style=None, postscript_name=None, full_name=None, system='auto', axes=(), variable_name=None, features=(), created_from_string='auto') italic_font: FontSpec = FontSpec(family=None, style=None, postscript_name=None, full_name=None, system='auto', axes=(), variable_name=None, features=(), created_from_string='auto')
kitty_mod: int = 5 kitty_mod: int = 5
leader: str = 'ctrl+space'
linux_bell_theme: str = '__custom' linux_bell_theme: str = '__custom'
linux_display_server: choices_for_linux_display_server = 'auto' linux_display_server: choices_for_linux_display_server = 'auto'
listen_on: str = 'none' listen_on: str = 'none'
@@ -706,7 +704,7 @@ class Options:
tab_switch_strategy: choices_for_tab_switch_strategy = 'previous' tab_switch_strategy: choices_for_tab_switch_strategy = 'previous'
tab_title_max_length: int = 0 tab_title_max_length: int = 0
tab_title_max_lines: int = 1 tab_title_max_lines: int = 1
tab_title_template: str = '{fmt.fg.red}{bell_symbol}{activity_symbol}{exit_status_symbol}{secure_input_symbol}{fmt.fg.tab}{tab.last_focused_progress_percent}{tab.active_wd_abbreviated} {title}' tab_title_template: str = '{fmt.fg.red}{bell_symbol}{activity_symbol}{exit_status_symbol}{secure_input_symbol}{fmt.fg.tab}{tab.last_focused_progress_percent}{title}'
tab_title_wrap: int = 0 tab_title_wrap: int = 0
term: str = 'xterm-kitty' term: str = 'xterm-kitty'
terminfo_type: choices_for_terminfo_type = 'path' terminfo_type: choices_for_terminfo_type = 'path'
@@ -904,10 +902,6 @@ defaults.map = [
KeyDefinition(trigger=SingleKey(mods=256, key=115), options=KeyMapOptions(when_focus_on='', new_mode='', mode='', on_unknown='beep', on_action='keep', timeout=None, allow_fallback=(KeyFallbackType.shifted, KeyFallbackType.alternate)), definition='paste_from_selection'), KeyDefinition(trigger=SingleKey(mods=256, key=115), options=KeyMapOptions(when_focus_on='', new_mode='', mode='', on_unknown='beep', on_action='keep', timeout=None, allow_fallback=(KeyFallbackType.shifted, KeyFallbackType.alternate)), definition='paste_from_selection'),
# paste_from_selection # paste_from_selection
KeyDefinition(trigger=SingleKey(mods=1, key=57348), definition='paste_from_selection'), KeyDefinition(trigger=SingleKey(mods=1, key=57348), definition='paste_from_selection'),
# paste_from_clipboard_history
KeyDefinition(trigger=SingleKey(mods=258, key=118), options=KeyMapOptions(when_focus_on='', new_mode='', mode='', on_unknown='beep', on_action='keep', timeout=None, allow_fallback=(KeyFallbackType.shifted, KeyFallbackType.alternate)), definition='paste_from_clipboard_history'),
# search_clipboard_history
KeyDefinition(trigger=SingleKey(mods=258, key=102), options=KeyMapOptions(when_focus_on='', new_mode='', mode='', on_unknown='beep', on_action='keep', timeout=None, allow_fallback=(KeyFallbackType.shifted, KeyFallbackType.alternate)), definition='search_clipboard_history'),
# pass_selection_to_program # pass_selection_to_program
KeyDefinition(trigger=SingleKey(mods=256, key=111), options=KeyMapOptions(when_focus_on='', new_mode='', mode='', on_unknown='beep', on_action='keep', timeout=None, allow_fallback=(KeyFallbackType.shifted, KeyFallbackType.alternate)), definition='pass_selection_to_program'), KeyDefinition(trigger=SingleKey(mods=256, key=111), options=KeyMapOptions(when_focus_on='', new_mode='', mode='', on_unknown='beep', on_action='keep', timeout=None, allow_fallback=(KeyFallbackType.shifted, KeyFallbackType.alternate)), definition='pass_selection_to_program'),
# scroll_line_up # scroll_line_up
@@ -936,8 +930,6 @@ defaults.map = [
KeyDefinition(trigger=SingleKey(mods=256, key=103), options=KeyMapOptions(when_focus_on='', new_mode='', mode='', on_unknown='beep', on_action='keep', timeout=None, allow_fallback=(KeyFallbackType.shifted, KeyFallbackType.alternate)), definition='show_last_command_output'), KeyDefinition(trigger=SingleKey(mods=256, key=103), options=KeyMapOptions(when_focus_on='', new_mode='', mode='', on_unknown='beep', on_action='keep', timeout=None, allow_fallback=(KeyFallbackType.shifted, KeyFallbackType.alternate)), definition='show_last_command_output'),
# search_scrollback # search_scrollback
KeyDefinition(trigger=SingleKey(mods=256, key=47), definition='search_scrollback'), KeyDefinition(trigger=SingleKey(mods=256, key=47), definition='search_scrollback'),
# search_scrollback_prompt
KeyDefinition(trigger=SingleKey(mods=258, key=115), definition='search_scrollback_prompt'),
# new_window # new_window
KeyDefinition(trigger=SingleKey(mods=256, key=57345), definition='new_window'), KeyDefinition(trigger=SingleKey(mods=256, key=57345), definition='new_window'),
# new_os_window # new_os_window
@@ -1032,16 +1024,12 @@ defaults.map = [
KeyDefinition(is_sequence=True, trigger=SingleKey(mods=256, key=112), rest=(SingleKey(key=110),), options=KeyMapOptions(when_focus_on='', new_mode='', mode='', on_unknown='beep', on_action='keep', timeout=None, allow_fallback=(KeyFallbackType.shifted, KeyFallbackType.alternate)), definition='kitten hints --type linenum'), KeyDefinition(is_sequence=True, trigger=SingleKey(mods=256, key=112), rest=(SingleKey(key=110),), options=KeyMapOptions(when_focus_on='', new_mode='', mode='', on_unknown='beep', on_action='keep', timeout=None, allow_fallback=(KeyFallbackType.shifted, KeyFallbackType.alternate)), definition='kitten hints --type linenum'),
# open_selected_hyperlink # open_selected_hyperlink
KeyDefinition(is_sequence=True, trigger=SingleKey(mods=256, key=112), rest=(SingleKey(key=121),), options=KeyMapOptions(when_focus_on='', new_mode='', mode='', on_unknown='beep', on_action='keep', timeout=None, allow_fallback=(KeyFallbackType.shifted, KeyFallbackType.alternate)), definition='kitten hints --type hyperlink'), KeyDefinition(is_sequence=True, trigger=SingleKey(mods=256, key=112), rest=(SingleKey(key=121),), options=KeyMapOptions(when_focus_on='', new_mode='', mode='', on_unknown='beep', on_action='keep', timeout=None, allow_fallback=(KeyFallbackType.shifted, KeyFallbackType.alternate)), definition='kitten hints --type hyperlink'),
# restore_last_session
KeyDefinition(trigger=SingleKey(mods=258, key=114), options=KeyMapOptions(when_focus_on='', new_mode='', mode='', on_unknown='beep', on_action='keep', timeout=None, allow_fallback=(KeyFallbackType.shifted, KeyFallbackType.alternate)), definition='restore_last_session'),
# show_kitty_doc # show_kitty_doc
KeyDefinition(trigger=SingleKey(mods=256, key=57364), definition='show_kitty_doc overview'), KeyDefinition(trigger=SingleKey(mods=256, key=57364), definition='show_kitty_doc overview'),
# command_palette # command_palette
KeyDefinition(trigger=SingleKey(mods=256, key=57366), definition='command_palette'), KeyDefinition(trigger=SingleKey(mods=256, key=57366), definition='command_palette'),
# file_manager # file_manager
KeyDefinition(trigger=SingleKey(mods=5, key=101), definition='launch --type=window-dock --dock-edge=left --dock-size=60 kitten file-manager'), KeyDefinition(trigger=SingleKey(mods=5, key=101), definition='launch --type=window-dock --dock-edge=right --dock-size=60 kitten file-manager'),
# keyboard_shortcuts
KeyDefinition(trigger=SingleKey(mods=258, key=104), definition='launch --type=window-dock --dock-edge=left --dock-size=60 kitty +kitten help'),
# toggle_fullscreen # toggle_fullscreen
KeyDefinition(trigger=SingleKey(mods=256, key=57374), definition='toggle_fullscreen'), KeyDefinition(trigger=SingleKey(mods=256, key=57374), definition='toggle_fullscreen'),
# toggle_maximized # toggle_maximized
-135
View File
@@ -1,135 +0,0 @@
#!/usr/bin/env python
# License: GPLv3 Copyright: 2026, Kovid Goyal <kovid at kovidgoyal.net>
"""In-place scrollback search.
The query parser and the matcher live here, away from the screen code, so that
they can be tested without a running terminal. A query can start with two
modifiers, in any order: ``\\c`` makes matching case sensitive and ``\\r``
treats the query as a regular expression. A doubled backslash escapes the
modifier syntax, so that the two prefixes can be searched for literally.
"""
from __future__ import annotations
import re
from collections.abc import Sequence
from dataclasses import dataclass, field
CASE_SENSITIVE_MODIFIER = 'c'
REGEX_MODIFIER = 'r'
# Mark numbers (see :opt:`mark1_background`) used to highlight the matches. The
# current match gets its own color so that it stands out from the other ones.
MATCH_COLOR = 1
CURRENT_MATCH_COLOR = 2
class InvalidQuery(ValueError):
pass
@dataclass(frozen=True)
class Query:
text: str
case_sensitive: bool = False
is_regex: bool = False
@property
def flags(self) -> int:
return 0 if self.case_sensitive else re.IGNORECASE
@dataclass(frozen=True)
class Match:
line: int
start: int
end: int
@dataclass
class ScrollbackSearch:
query: Query
pattern: re.Pattern[str]
matches: list[Match] = field(default_factory=list)
index: int = 0
total_lines: int = 0
def __len__(self) -> int:
return len(self.matches)
@property
def current_match(self) -> Match | None:
return self.matches[self.index] if self.matches else None
def marker_spans(self, lines: Sequence[str]) -> dict[str, tuple[tuple[int, int, int], ...]]:
"""Spans to highlight, keyed by the text of the line holding them.
Marker functions are called once per line with only its text, never with
its number, so the spans are grouped by line text. Lines that are
identical to the current one are therefore highlighted alike, which the
user cannot tell apart since their text is the same.
"""
current = self.current_match
spans: dict[str, list[tuple[int, int, int]]] = {}
for match in self.matches:
color = CURRENT_MATCH_COLOR if match == current else MATCH_COLOR
spans.setdefault(lines[match.line], []).append((match.start, match.end, color))
return {text: tuple(found) for text, found in spans.items()}
def parse_query(raw: str) -> Query:
text = (raw or '').strip()
case_sensitive = is_regex = False
while len(text) > 1 and text[0] == '\\':
modifier = text[1].lower()
if modifier == '\\':
# A doubled backslash stands for a literal one and ends the modifier
# section, which is the only way to search for \c or \r themselves.
text = text[1:]
break
if modifier == CASE_SENSITIVE_MODIFIER:
case_sensitive = True
elif modifier == REGEX_MODIFIER:
is_regex = True
else:
# Not a modifier, the backslash is part of the searched text.
break
text = text[2:]
text = text.strip()
if not text:
raise InvalidQuery('the search query is empty')
return Query(text, case_sensitive, is_regex)
def compile_query(query: Query) -> re.Pattern[str]:
source = query.text if query.is_regex else re.escape(query.text)
try:
return re.compile(source, query.flags)
except re.error as err:
raise InvalidQuery(f'invalid regular expression: {err}') from err
def find_matches(lines: list[str] | tuple[str, ...], query: Query, pattern: re.Pattern[str] | None = None) -> list[Match]:
pat = pattern if pattern is not None else compile_query(query)
ans: list[Match] = []
append = ans.append
for line_number, line in enumerate(lines):
for match in pat.finditer(line):
# Empty matches cannot be navigated to and would make the count
# meaningless, so they are ignored.
if match.end() > match.start():
append(Match(line_number, match.start(), match.end()))
return ans
def scroll_offset_for(match: Match, total_lines: int, visible_lines: int) -> int:
"""Number of lines to scroll up so that the match is visible.
The searched text is the history buffer followed by the visible screen, so
line 0 is the oldest line. The match is placed roughly a third of the way
down the screen, except near the top and bottom of the scrollback.
"""
history = max(0, total_lines - visible_lines)
margin = max(0, visible_lines // 3)
return max(0, min(history, history - match.line + margin))
+1 -9
View File
@@ -327,15 +327,7 @@ def create_sessions(
env_when_no_session: dict[str, str] | None = None, env_when_no_session: dict[str, str] | None = None,
) -> Iterator[Session]: ) -> Iterator[Session]:
if args and args.session: if args and args.session:
if args.session == 'last': if args.session == 'none':
from .session_restore import load_last_session, state_path
raw = load_last_session()
if raw:
yield from parse_session(raw, opts, session_arg='last', session_path=state_path())
return
log_error('There is no saved session to restore, starting a new session instead')
elif args.session == 'none':
default_session = 'none' default_session = 'none'
else: else:
session_arg = args.session session_arg = args.session
-162
View File
@@ -1,162 +0,0 @@
#!/usr/bin/env python
# License: GPL v3 Copyright: 2026, Kovid Goyal <kovid at kovidgoyal.net>
# Keep the state of the session that was last in use so that `kitty --session=last` can restore it.
#
# The state is stored in the XDG state directory, is bounded in size and is only ever read when the
# user explicitly asks for it, since restoring an unexpected state is worse than not restoring
# anything. Anything that cannot be read back is discarded instead of preventing startup.
import json
import os
import time
from contextlib import suppress
from typing import TYPE_CHECKING, Any
from .config import atomic_save
from .utils import log_error
if TYPE_CHECKING:
from .typing_compat import BossType
STATE_VERSION = 1
MAX_STATE_SIZE = 1024 * 1024
STATE_FILE_NAME = 'last-session.json'
def state_dir() -> str:
base = os.environ.get('XDG_STATE_HOME') or os.path.join(os.path.expanduser('~'), '.local', 'state')
return os.path.join(base, 'kitty')
def state_path() -> str:
return os.path.join(state_dir(), STATE_FILE_NAME)
def serialize_state(session: str, saved_at: float | None = None) -> bytes:
state = {'version': STATE_VERSION, 'saved_at': time.time() if saved_at is None else saved_at, 'session': session}
return json.dumps(state, ensure_ascii=False).encode('utf-8')
def save_last_session(session: str) -> bool:
"""Store the session text, returning False when it cannot be stored."""
if not session.strip():
return False
if len(session) > MAX_STATE_SIZE:
log_error(f'Not saving the last session as it is larger than {MAX_STATE_SIZE} characters, use save_as_session for large sessions')
return False
path = state_path()
try:
os.makedirs(os.path.dirname(path), exist_ok=True)
atomic_save(serialize_state(session), path)
except OSError as e:
log_error(f'Failed to save the last session to {path}: {e}')
return False
return True
def prune_missing_directories(session: str) -> tuple[str, int]:
"""Drop cd directives whose directory is gone, so that a stale state does not fail to restore."""
lines: list[str] = []
pruned = 0
for line in session.splitlines():
stripped = line.strip()
if stripped.startswith('cd ') and stripped[3:].strip():
raw = stripped[3:].strip().strip('"\'')
path = os.path.expanduser(raw)
if os.path.isabs(path) and not os.path.isdir(path):
pruned += 1
continue
lines.append(line)
return '\n'.join(lines), pruned
def discard_last_session() -> None:
try:
os.remove(state_path())
except FileNotFoundError:
pass
except OSError as e:
log_error(f'Failed to delete the unreadable last session: {e}')
def parse_state(raw: bytes) -> str:
try:
parsed: Any = json.loads(raw)
except (ValueError, UnicodeDecodeError) as e:
raise ValueError(f'not valid JSON: {e}') from e
if not isinstance(parsed, dict):
raise ValueError('not a JSON object')
version = parsed.get('version')
if not isinstance(version, int):
raise ValueError('missing state version')
if version > STATE_VERSION:
raise ValueError(f'state version {version} is newer than the supported version {STATE_VERSION}')
session = parsed.get('session')
if not isinstance(session, str):
raise ValueError('missing session text')
return session
def load_last_session() -> str:
"""Return the stored session text, or an empty string when there is nothing usable."""
path = state_path()
try:
with open(path, 'rb') as f:
raw = f.read(MAX_STATE_SIZE + 1)
except FileNotFoundError:
return ''
except OSError as e:
log_error(f'Failed to read the last session from {path}: {e}')
return ''
if len(raw) > MAX_STATE_SIZE:
log_error(f'Discarding the last session in {path} as it is larger than {MAX_STATE_SIZE} bytes')
discard_last_session()
return ''
try:
session = parse_state(raw)
except ValueError as e:
log_error(f'Discarding the last session in {path} as it cannot be read: {e}')
discard_last_session()
return ''
session, pruned = prune_missing_directories(session)
if pruned:
log_error(f'Dropped {pruned} working directory directive(s) from the last session as the directories no longer exist')
return session
def save_session_of(boss: 'BossType') -> None:
"""Save the state of a running kitty instance, never raising so that it cannot break quitting."""
from .session import default_save_as_session_opts
try:
opts = default_save_as_session_opts()
opts.os_window_geometry = True
session = '\n'.join(boss.serialize_state_as_session('', opts))
save_last_session(session)
except Exception as e:
log_error(f'Failed to save the last session: {e}')
def restore_last_session_into(boss: 'BossType') -> bool:
"""Add the tabs and windows of the last saved session to a running kitty.
Returns False when there is nothing to restore. The saved state is a JSON document, so it is
handed to the session parser through a short lived file rather than duplicating the parsing.
"""
raw = load_last_session()
if not raw:
return False
import tempfile
from .session import create_session
fd, path = tempfile.mkstemp(prefix='last-session-', suffix='.kitty-session')
try:
with open(fd, 'w', encoding='utf-8') as f:
f.write(raw)
create_session(boss, path)
finally:
with suppress(OSError):
os.unlink(path)
return True
-11
View File
@@ -927,17 +927,6 @@ class Tab: # {{{
restored_scrollback: bytes = b'', restored_scrollback: bytes = b'',
) -> Window: ) -> Window:
"Create a new window. When dock is specified, the window is docked to dock_owner or to the tab if dock_owner is None." "Create a new window. When dock is specified, the window is docked to dock_owner or to the tab if dock_owner is None."
# A special window opened over another one, or docked next to it, needs
# to know which shell it belongs to: the file manager uses it to find
# the session file where that shell publishes its working directory. A
# dock follows a window group, so its initial parent is the active
# window of the tab it is created in.
parent_window_id = overlay_for
if parent_window_id is None and dock is not None and (aw := self.active_window) is not None:
parent_window_id = aw.id
if parent_window_id is not None:
env = dict(env or {})
env['KITTY_SPECIAL_WINDOW_PARENT'] = str(parent_window_id)
cs = WindowCreationSpec( cs = WindowCreationSpec(
use_shell=use_shell, use_shell=use_shell,
cmd=cmd, cmd=cmd,
-156
View File
@@ -148,7 +148,6 @@ if TYPE_CHECKING:
from .fast_data_types import MousePosition from .fast_data_types import MousePosition
from .file_transmission import FileTransmission from .file_transmission import FileTransmission
from .notifications import OnlyWhen from .notifications import OnlyWhen
from .scrollback_search import ScrollbackSearch
class CwdRequestType(Enum): class CwdRequestType(Enum):
@@ -826,12 +825,6 @@ class Window:
self.actions_on_focus_change: list[Callable[['Window', bool], None]] = [] self.actions_on_focus_change: list[Callable[['Window', bool], None]] = []
self.actions_on_removal: list[Callable[['Window'], None]] = [] self.actions_on_removal: list[Callable[['Window'], None]] = []
self.current_marker_spec: tuple[str, str | tuple[tuple[int, str], ...]] | None = None self.current_marker_spec: tuple[str, str | tuple[tuple[int, str], ...]] | None = None
self.scrollback_search: ScrollbackSearch | None = None
self.scrollback_search_spans: dict[str, tuple[tuple[int, int, int], ...]] = {}
self.scrollback_search_mode: str = ''
self.scrollback_search_saved_marker: tuple[str, str | tuple[tuple[int, str], ...]] | None = None
self.scrollback_search_saved_title: str | None = None
self.actions_on_focus_change.append(self._on_focus_change_clear_scrollback_search)
self.kitten_result_processors: list[Callable[['Window', Any], None]] = [] self.kitten_result_processors: list[Callable[['Window', Any], None]] = []
self.child_is_launched = False self.child_is_launched = False
self.restored_scrollback = b'' self.restored_scrollback = b''
@@ -2673,155 +2666,6 @@ class Window:
w.screen.paste_bytes(sanitized) w.screen.paste_bytes(sanitized)
w.send_key('enter') w.send_key('enter')
@ac(
'sc',
"""
Search the scrollback in place, highlighting every match. Prefix the query with \\c for a case
sensitive search and with \\r for a regular expression. To search for those two strings literally,
write a double backslash instead (``\\\\c`` and ``\\\\r``). Matches are navigated with n and N and
the search ends with Escape. The [current/total] counter is shown in the window title and the
current match uses the second mark color.
""",
)
def search_scrollback_prompt(self) -> bool | None:
if not self.screen.is_main_linebuf():
return True
def done(text: str) -> None:
if text:
self.start_scrollback_search(text)
else:
self.clear_scrollback_search()
get_boss().get_line(
_(
'Search the scrollback. Prefix the query with \\c for a case sensitive search and \\r for a regular expression.'
' Write a double backslash to search for those strings literally.'
),
done,
window=self,
prompt=_('search> '),
window_title=_('Search scrollback'),
)
return None
def scrollback_search_lines(self) -> list[str]:
# Read the history buffer and the visible screen directly instead of using
# as_text(), so that line numbers are the ones scrolling actions use.
lines: list[str] = []
self.screen.as_text_for_history_buf(lines.append, False, True)
self.screen.as_text(lines.append, False, True)
return [line.replace('\r', '').replace('\n', '') for line in lines]
def start_scrollback_search(self, raw_query: str) -> None:
from .scrollback_search import InvalidQuery, ScrollbackSearch, compile_query, find_matches, parse_query
try:
query = parse_query(raw_query)
pattern = compile_query(query)
except InvalidQuery as err:
get_boss().show_error(_('Invalid search query'), str(err))
return
lines = self.scrollback_search_lines()
matches = find_matches(lines, query, pattern)
if not matches:
from .fast_data_types import ring_bell
ring_bell(self.os_window_id)
return
self.clear_scrollback_search()
search = ScrollbackSearch(query, pattern, matches, total_lines=len(lines))
self.scrollback_search = search
self.scrollback_search_spans = search.marker_spans(lines)
self.scrollback_search_saved_marker = self.current_marker_spec
self.scrollback_search_saved_title = self.override_title
self._push_scrollback_search_mode()
self._goto_scrollback_match(0)
@ac('sc', 'Stop the in-place scrollback search and remove its highlights')
def clear_scrollback_search(self) -> None:
if self.scrollback_search is None:
return
self.scrollback_search = None
self.scrollback_search_spans = {}
self.screen.set_marker()
self.current_marker_spec = None
saved = self.scrollback_search_saved_marker
self.scrollback_search_saved_marker = None
if saved is not None:
# Restore the marker that was displayed before the search started.
from .marks import marker_from_spec
ftype, spec = saved
self.screen.set_marker(marker_from_spec(ftype, spec, 0))
self.current_marker_spec = saved
self.set_title(self.scrollback_search_saved_title)
self.scrollback_search_saved_title = None
if self.scrollback_search_mode:
get_boss().mappings.pop_keyboard_mode_if_is(self.scrollback_search_mode)
self.scrollback_search_mode = ''
@ac('sc', 'Jump to the next match of the in-place scrollback search')
def scrollback_search_next(self) -> bool | None:
return self._scrollback_search_step(1)
@ac('sc', 'Jump to the previous match of the in-place scrollback search')
def scrollback_search_prev(self) -> bool | None:
return self._scrollback_search_step(-1)
def _scrollback_search_step(self, step: int) -> bool | None:
search = self.scrollback_search
if search is None:
return None
if not self.screen.is_main_linebuf():
return True
self._goto_scrollback_match(search.index + step)
return None
def _goto_scrollback_match(self, index: int) -> None:
from .scrollback_search import scroll_offset_for
search = self.scrollback_search
if search is None or not search.matches:
return
search.index = index % len(search.matches)
match = search.matches[search.index]
self.set_title(f'[{search.index + 1}/{len(search.matches)}] {search.query.text}')
self._refresh_scrollback_search_marker()
self.screen.scroll_to_absolute(scroll_offset_for(match, search.total_lines, self.screen.lines))
def _refresh_scrollback_search_marker(self) -> None:
from .marks import marker_from_spans
# Clear first, as set_marker() only releases the previous callable when
# it is called without one. Marking every line again is needed anyway to
# recolor the match that was current until now.
self.screen.set_marker()
self.screen.set_marker(marker_from_spans(self.scrollback_search_spans))
def _push_scrollback_search_mode(self) -> None:
from .fast_data_types import GLFW_FKEY_ESCAPE, GLFW_MOD_SHIFT
from .options.utils import KeyboardMode, KeyDefinition, SingleKey
km = KeyboardMode('__scrollback_search__')
km.on_unknown = 'passthrough'
km.on_action = 'keep'
next_match = KeyDefinition(definition='scrollback_search_next')
prev_match = KeyDefinition(definition='scrollback_search_prev')
km.keymap[SingleKey(key=ord('n'))].append(next_match)
km.keymap[SingleKey(mods=GLFW_MOD_SHIFT, key=ord('n'))].append(prev_match)
km.keymap[SingleKey(mods=GLFW_MOD_SHIFT, key=ord('N'))].append(prev_match)
km.keymap[SingleKey(key=GLFW_FKEY_ESCAPE)].append(KeyDefinition(definition='clear_scrollback_search'))
self.scrollback_search_mode = km.name
get_boss().mappings._push_keyboard_mode(km)
def _on_focus_change_clear_scrollback_search(self, window: 'Window', focused: bool) -> None:
# The n/N bindings live in a temporary keyboard mode, so the search must
# end when this window stops being the one receiving keys.
if not focused and self.scrollback_search is not None:
self.clear_scrollback_search()
def show_cmd_output(self, which: CommandOutput, title: str = 'Command output', as_ansi: bool = True, add_wrap_markers: bool = True) -> None: def show_cmd_output(self, which: CommandOutput, title: str = 'Command output', as_ansi: bool = True, add_wrap_markers: bool = True) -> None:
text = self.cmd_output(which, as_ansi=as_ansi, add_wrap_markers=add_wrap_markers) text = self.cmd_output(which, as_ansi=as_ansi, add_wrap_markers=add_wrap_markers)
text = text.replace('\r\n', '\n').replace('\r', '\n') text = text.replace('\r\n', '\n').replace('\r', '\n')
-146
View File
@@ -1,146 +0,0 @@
#!/usr/bin/env python
# License: GPL v3 Copyright: 2026, Kovid Goyal <kovid at kovidgoyal.net>
from kitty.clipboard_history import ClipboardHistory, match_score, text_from_mime_data
from .base import BaseTest
class TestClipboardHistory(BaseTest):
def test_newest_first(self) -> None:
h = ClipboardHistory()
self.assertFalse(h)
self.assertTrue(h.add('one'))
self.assertTrue(h.add('two'))
self.ae(h.entries(), ('two', 'one'))
self.ae(list(h), ['two', 'one'])
self.ae(len(h), 2)
self.ae(h[0], 'two')
def test_empty_and_blank_text_is_ignored(self) -> None:
h = ClipboardHistory()
self.assertFalse(h.add(''))
self.assertFalse(h.add(' \n\t'))
self.ae(len(h), 0)
def test_private_entries_are_never_recorded(self) -> None:
h = ClipboardHistory()
self.assertFalse(h.add('hunter2', private=True))
self.ae(len(h), 0)
self.assertTrue(h.add('public'))
self.assertFalse(h.add('hunter2', private=True))
self.ae(h.entries(), ('public',))
def test_duplicates_move_to_the_top(self) -> None:
h = ClipboardHistory()
for x in ('a', 'b', 'a'):
h.add(x)
self.ae(h.entries(), ('a', 'b'))
def test_entry_count_is_bounded(self) -> None:
h = ClipboardHistory(max_entries=3)
for x in ('a', 'b', 'c', 'd', 'e'):
h.add(x)
self.ae(h.entries(), ('e', 'd', 'c'))
def test_total_size_is_bounded(self) -> None:
h = ClipboardHistory(max_entries=100, max_total_chars=10)
h.add('12345')
h.add('67890')
h.add('abcde')
self.assertLessEqual(sum(len(x) for x in h.entries()), 10)
self.ae(h.entries()[0], 'abcde')
def test_oversized_entries_are_ignored(self) -> None:
h = ClipboardHistory(max_entry_chars=5)
self.assertFalse(h.add('123456'))
self.assertTrue(h.add('12345'))
self.ae(h.entries(), ('12345',))
def test_clear(self) -> None:
h = ClipboardHistory()
h.add('a')
h.clear()
self.ae(len(h), 0)
self.assertFalse(h)
# clearing resets the accounting, so new entries are kept even after large ones
self.assertTrue(h.add('b'))
self.ae(h.entries(), ('b',))
def test_search(self) -> None:
h = ClipboardHistory()
for x in ('make test', 'make build', 'git status', 'echo make'):
h.add(x)
self.ae(h.search(''), h.entries())
self.ae(h.search(' '), h.entries())
# An earlier substring match ranks first, ties keep the newest entry first
self.ae(h.search('make'), ('make build', 'make test', 'echo make'))
self.ae(h.search('mkb'), ('make build',))
self.ae(h.search('zzz'), ())
def test_entries_carry_the_time_they_were_copied(self) -> None:
h = ClipboardHistory()
self.assertTrue(h.add('first', timestamp=100.0))
self.assertTrue(h.add('second', timestamp=200.0))
self.ae(h.entries(), ('second', 'first'))
self.ae(h.entries_with_times(), (('second', 200.0), ('first', 100.0)))
# A repeated copy moves the text and its new time to the top
self.assertTrue(h.add('first', timestamp=300.0))
self.ae(h.entries(), ('first', 'second'))
self.ae(h.entries_with_times(), (('first', 300.0), ('second', 200.0)))
self.ae(h.search_with_times('sec'), (('second', 200.0),))
self.ae(h.search('sec'), ('second',))
def test_substring_matches_rank_before_subsequences(self) -> None:
h = ClipboardHistory()
h.add('xkcd')
h.add('kcd')
self.ae(h.search('kcd'), ('kcd', 'xkcd'))
def test_match_score(self) -> None:
self.ae(match_score('', 'anything'), 0)
self.ae(match_score('abc', 'xxabc'), 2)
self.assertGreater(match_score('abc', 'a-x-b-x-c'), 2)
self.ae(match_score('abc', 'cba'), -1)
self.ae(match_score('Abc', 'xxabc'), 2) # matching is case insensitive
def test_text_from_bytes(self) -> None:
self.ae(text_from_mime_data(b'hello'), 'hello')
self.ae(text_from_mime_data('not bytes'), '')
self.ae(text_from_mime_data(None), '')
self.ae(text_from_mime_data(b'a\xffb'), 'a\ufffdb')
def test_text_from_chunker(self) -> None:
# OSC 52 writes are streamed, so the clipboard stores a chunker factory not bytes
chunks = [b'first ', b'second', b'']
def factory():
it = iter(chunks)
def chunker():
return next(it, b'')
return chunker
self.ae(text_from_mime_data(factory), 'first second')
def test_text_from_chunker_is_bounded(self) -> None:
def factory():
remaining = [b'x' * 1000] * 1000
it = iter(remaining)
def chunker():
return next(it, b'')
return chunker
ans = text_from_mime_data(factory, max_chars=10)
self.assertLessEqual(len(ans), 40)
self.assertTrue(ans)
def test_no_persistence_api(self) -> None:
# The history is deliberately memory only: there is no save/load entry point to call
h = ClipboardHistory()
self.assertFalse(hasattr(h, 'save'))
self.assertFalse(hasattr(h, 'load'))
self.assertFalse(hasattr(h, 'path'))
-49
View File
@@ -279,52 +279,3 @@ class TestCommandPalette(BaseTest):
def test_unmapped_actions_sorted_order(self): def test_unmapped_actions_sorted_order(self):
# Covered by test_collect_keys_bindings_sorted # Covered by test_collect_keys_bindings_sorted
pass pass
def test_leader_prefix_bindings(self):
from kittens.command_palette.main import collect_leader_data
from kitty.options.utils import parse_map, parse_shortcut
opts = self.set_options({'leader': 'ctrl+space'})
for spec in ('ctrl+space>n new_os_window', 'ctrl+space>w new_window', 'ctrl+space>n new_os_window'):
for kd in parse_map(spec):
kd = kd.resolve_and_copy(opts.kitty_mod)
opts.keyboard_modes[''].keymap.setdefault(kd.trigger, []).append(kd)
data = collect_leader_data(opts, parse_shortcut('ctrl+space'))
leader = data['leader']
self.ae(leader['prefix'], 'ctrl+space')
self.ae([b['key'] for b in leader['bindings']], ['n', 'w'], 'Duplicate continuations should collapse')
self.ae(leader['bindings'][0]['action'], 'new_os_window')
self.ae(leader['bindings'][1]['action'], 'new_window')
self.assertTrue(leader['bindings'][0]['help'], 'Bindings should carry their help text')
def test_leader_option(self):
from kitty.keys import leader_key_from_options
opts = self.set_options({'leader': 'none'})
self.assertIsNone(leader_key_from_options(opts))
self.assertIsNone(opts.leader_key)
opts = self.set_options({'leader': 'ctrl+space'})
self.assertIsNotNone(leader_key_from_options(opts))
self.assertIsNotNone(opts.leader_key)
def test_append_map_to_config(self):
import os
import tempfile
from kitty.config import append_map_to_config
with tempfile.TemporaryDirectory() as tdir:
path = os.path.join(tdir, 'kitty.conf')
self.ae(append_map_to_config('ctrl+u', 'new_os_window', path), path)
self.ae(append_map_to_config('ctrl+j', 'new_tab', path), path)
with open(path) as f:
self.ae(f.read().splitlines(), ['map ctrl+u new_os_window', 'map ctrl+j new_tab'])
# A config file without a trailing newline must not get a mangled line
with open(path, 'w') as f:
f.write('font_size 12')
append_map_to_config('ctrl+k', 'new_window', path)
with open(path) as f:
self.ae(f.read().splitlines(), ['font_size 12', 'map ctrl+k new_window'])
-13
View File
@@ -126,16 +126,6 @@ class TestDocks(BaseTest):
content, placements = carve_docks(Region((0, 0, -1, -1, 0, 0)), groups, CELL_WIDTH, CELL_HEIGHT) content, placements = carve_docks(Region((0, 0, -1, -1, 0, 0)), groups, CELL_WIDTH, CELL_HEIGHT)
self.ae([r.height for g, r in placements], [0, 0]) self.ae([r.height for g, r in placements], [0, 0])
# A dock at the right is placed against the right edge of what remains,
# the same way a dock at the left is placed against the left edge
groups = []
left, right = dock('left', '10%'), dock('right', '5%')
content, placements = carve_docks(VIEWPORT, groups, CELL_WIDTH, CELL_HEIGHT)
regions = {g.id: rect(r) for g, r in placements}
self.ae(regions[left.id], (0, 0, 100, 600))
self.ae(regions[right.id], (950, 0, 1000, 600))
self.ae(rect(content), (100, 0, 950, 600))
def test_tab_docks(self): def test_tab_docks(self):
q = make_layout(Tall) q = make_layout(Tall)
windows = make_windows(q, 2) windows = make_windows(q, 2)
@@ -193,9 +183,6 @@ class TestDocks(BaseTest):
self.assertTrue(rect(r)[0] >= allocated.left and rect(r)[2] <= allocated.left + allocated.width) self.assertTrue(rect(r)[0] >= allocated.left and rect(r)[2] <= allocated.left + allocated.width)
self.ae(rect(dock_regions[0])[1], allocated.top + allocated.height - 2 * CELL_HEIGHT - 2 * DECORATION) self.ae(rect(dock_regions[0])[1], allocated.top + allocated.height - 2 * CELL_HEIGHT - 2 * DECORATION)
self.ae(dock_regions[1].width, allocated.width // 4) self.ae(dock_regions[1].width, allocated.width // 4)
# The dock at the right sits past the content, at the right of the area
self.assertGreaterEqual(rect(dock_regions[1])[0], rect(content)[2])
self.assertLessEqual(rect(dock_regions[1])[2], allocated.left + allocated.width)
self.check_no_overlaps(windows) self.check_no_overlaps(windows)
# The decorations chosen by the layout for the owner are preserved # The decorations chosen by the layout for the owner are preserved
self.ae(main.geometry.spaces.left - main.geometry.compensatory.left, DECORATION) self.ae(main.geometry.spaces.left - main.geometry.compensatory.left, DECORATION)
-79
View File
@@ -1,79 +0,0 @@
#!/usr/bin/env python
# License: GPLv3 Copyright: 2026, FWS
from unittest.mock import MagicMock, patch
from kittens.file_manager.main import change_directory, handle_result
from .base import BaseTest
class TestFileManager(BaseTest):
def test_file_manager(self):
"""The documented defaults are the ones the panel starts with."""
from kittens.file_manager.main import definition
options = {o.name: o for o in definition.iter_all_options()}
for name, expected in (
('show_hidden', 'no'),
('sort_by', 'name'),
('sync_cwd', 'yes'),
):
self.assertIn(name, options, f'{name} must be a documented option')
self.ae(options[name].defval_as_string, expected, name)
self.assertTrue(options[name].long_text, f'{name} must have help text')
def test_change_directory_at_the_prompt(self):
w = MagicMock()
w.at_prompt = True
change_directory(w, '/tmp/a b')
w.write_to_child.assert_called_once_with("cd '/tmp/a b'\r")
w.paste_text.assert_not_called()
def test_change_directory_while_a_program_runs(self):
# While a program owns the terminal the command is only pasted, so that
# it can be reviewed instead of being fed to the program's stdin.
w = MagicMock()
w.at_prompt = False
change_directory(w, "/tmp/it's")
w.paste_text.assert_called_once_with("cd '/tmp/it'\"'\"'s'")
w.write_to_child.assert_not_called()
def test_result_changes_the_target_window_directory(self):
boss = MagicMock()
window = MagicMock()
boss.window_id_map.get.return_value = window
with patch('kittens.file_manager.main.change_directory') as cd:
handle_result([], {'action': 'cd', 'path': '/tmp/project'}, 42, boss)
cd.assert_called_once_with(window, '/tmp/project')
boss.ring_bell_if_allowed.assert_not_called()
def test_result_with_sync_does_not_type_into_the_shell(self):
# With sync_cwd on, the panel wrote the directory in the session file
# and the shell hook applies it; typing a second cd would move twice.
boss = MagicMock()
with patch('kittens.file_manager.main.change_directory') as cd:
handle_result([], {'action': 'cd', 'path': '/tmp/project', 'sync': True}, 42, boss)
cd.assert_not_called()
boss.window_id_map.get.assert_not_called()
def test_result_without_the_target_window_rings_the_bell(self):
boss = MagicMock()
boss.window_id_map.get.return_value = None
handle_result([], {'action': 'cd', 'path': '/tmp/project'}, 42, boss)
boss.ring_bell_if_allowed.assert_called_once()
def test_result_ignores_incomplete_payloads(self):
boss = MagicMock()
with patch('kittens.file_manager.main.change_directory') as cd:
handle_result([], {}, 42, boss)
handle_result([], {'action': 'open', 'path': '/tmp'}, 42, boss)
handle_result([], {'action': 'cd'}, 42, boss)
cd.assert_not_called()
boss.ring_bell_if_allowed.assert_not_called()
-28
View File
@@ -834,31 +834,3 @@ class TestMouse(BaseTest):
ac([], 4) ac([], 4)
self.assertTrue(s.callbacks.wtcbuf, 'the wheel event was not reported to the program') self.assertTrue(s.callbacks.wtcbuf, 'the wheel event was not reported to the program')
parse_bytes(s, b'\x1b[?1000l') parse_bytes(s, b'\x1b[?1000l')
def test_docked_window_receives_clicks_at_any_edge(self):
from kitty.fast_data_types import mock_window_under_mouse
s = self.create_screen(cols=140, lines=30)
w = create_mock_window(s)
terminal, right_dock = (0, 0, 1000, 600), (1000, 0, 1400, 600)
left_dock, offset_terminal = (0, 0, 400, 600), (400, 0, 1400, 600)
def under(first, second, x, y):
return mock_window_under_mouse(w, *first, *second, x, y)
# A dock at the right receives the clicks in its own area and the
# terminal receives the clicks in the area left over
self.ae(under(terminal, right_dock, 500, 300), 1)
self.ae(under(terminal, right_dock, 999, 300), 1)
self.ae(under(terminal, right_dock, 1000, 300), 2)
self.ae(under(terminal, right_dock, 1200, 300), 2)
# Swapping the two areas over must give the same answer for a dock at
# the left, so the hit test does not depend on the edge
self.ae(under(left_dock, offset_terminal, 500, 300), 2)
self.ae(under(left_dock, offset_terminal, 100, 300), 1)
self.ae(under(left_dock, offset_terminal, 399, 300), 1)
# The first window wins when two areas overlap, as with an overlay
self.ae(under(terminal, (500, 0, 1400, 600), 700, 300), 1)
# A window with an empty area is never hit, even inside the other one
self.ae(under(terminal, (0, 0, 0, 0), 1200, 300), 0)
self.ae(under((0, 0, 0, 0), right_dock, 1200, 300), 2)
-25
View File
@@ -29,31 +29,6 @@ class TestConfParsing(BaseTest):
def test_conf_parsing(self): def test_conf_parsing(self):
conf_parsing(self) conf_parsing(self)
def test_default_shortcuts_have_no_duplicate_trigger(self):
from kitty.config import load_config
opts = load_config(overrides=())
keymap = opts.keyboard_modes[''].keymap
# The file manager deliberately takes kitty_mod+e over from open_url, a
# decision documented in the changelog. Every other collision means the
# last definition wins silently and one of the two actions is unreachable.
accepted = {frozenset(('launch', 'open_url_with_hints'))}
for key, defns in keymap.items():
actions = {d.definition.split()[0] for d in defns}
if len(actions) > 1 and frozenset(actions) not in accepted:
self.fail(f'{key!r} is claimed by several actions: {sorted(actions)}')
def test_default_search_shortcut(self):
from kitty.config import load_config
opts = load_config(overrides=())
keymap = opts.keyboard_modes[''].keymap
keys = [key for key, defns in keymap.items() if any(d.definition.split()[0] == 'search_scrollback_prompt' for d in defns)]
self.ae(len(keys), 1, 'the in-place search must have exactly one default shortcut')
# A shared trigger means the last definition wins silently and the search
# never opens, which is what happened with move_window_forward.
self.ae([d.definition.split()[0] for d in keymap[keys[0]]], ['search_scrollback_prompt'])
def test_launcher(self): def test_launcher(self):
launcher(self) launcher(self)
-127
View File
@@ -1,127 +0,0 @@
#!/usr/bin/env python
# License: GPLv3 Copyright: 2026, Kovid Goyal <kovid at kovidgoyal.net>
import re
import time
from kitty.scrollback_search import (
CURRENT_MATCH_COLOR,
MATCH_COLOR,
InvalidQuery,
Match,
ScrollbackSearch,
compile_query,
find_matches,
parse_query,
scroll_offset_for,
)
from .base import BaseTest
class TestScrollbackSearch(BaseTest):
def test_parse_query(self):
q = parse_query('needle')
self.ae((q.text, q.case_sensitive, q.is_regex), ('needle', False, False))
self.assertTrue(compile_query(q).flags & re.IGNORECASE)
q = parse_query(' padded ')
self.ae(q.text, 'padded')
def test_parse_query_modifiers(self):
q = parse_query('\\c Needle')
self.ae((q.text, q.case_sensitive, q.is_regex), ('Needle', True, False))
self.ae(compile_query(q).flags & re.IGNORECASE, 0)
q = parse_query('\\r a.c')
self.ae((q.text, q.case_sensitive, q.is_regex), ('a.c', False, True))
for raw in ('\\r\\c a+b', '\\c\\r a+b', '\\C\\R a+b'):
q = parse_query(raw)
self.ae((q.text, q.case_sensitive, q.is_regex), ('a+b', True, True), raw)
with self.assertRaises(InvalidQuery):
parse_query('')
with self.assertRaises(InvalidQuery):
parse_query(' ')
with self.assertRaises(InvalidQuery):
parse_query('\\c')
with self.assertRaises(InvalidQuery):
compile_query(parse_query('\\r ('))
def test_parse_query_escaped_backslash(self):
# A doubled backslash searches text starting with a backslash instead of
# being read as a modifier, so both modifier prefixes remain reachable.
for raw, expected in (('\\\\c', '\\c'), ('\\\\r', '\\r'), ('\\\\C', '\\C'), ('\\\\', '\\')):
with self.subTest(raw=raw):
q = parse_query(raw)
self.ae((q.text, q.case_sensitive, q.is_regex), (expected, False, False))
# Modifiers still combine with an escaped prefix in the searched text
q = parse_query('\\c\\\\r')
self.ae((q.text, q.case_sensitive, q.is_regex), ('\\r', True, False))
# The escaped prefix is matched like any other text, case insensitively
# by default, and the case sensitive modifier still applies to it.
matches = find_matches(['a \\c b', 'a \\C b'], parse_query('\\\\c'))
self.ae([(m.line, m.start, m.end) for m in matches], [(0, 2, 4), (1, 2, 4)])
matches = find_matches(['a \\c b', 'a \\C b'], parse_query('\\c\\\\c'))
self.ae([(m.line, m.start, m.end) for m in matches], [(0, 2, 4)])
def test_find_matches_plain(self):
lines = ['needle at start', 'Needle again', 'nothing', 'a needle here']
matches = find_matches(lines, parse_query('needle'))
self.ae([(m.line, m.start, m.end) for m in matches], [(0, 0, 6), (1, 0, 6), (3, 2, 8)])
matches = find_matches(lines, parse_query('\\c Needle'))
self.ae([(m.line, m.start, m.end) for m in matches], [(1, 0, 6)])
# Regex metacharacters are literal in a plain query
self.ae(find_matches(['a+b', 'aab'], parse_query('a+b')), [Match(0, 0, 3)])
def test_find_matches_regex(self):
matches = find_matches(['abc abc', 'nothing here'], parse_query('\\r a.c'))
self.ae([(m.line, m.start, m.end) for m in matches], [(0, 0, 3), (0, 4, 7)])
# Empty matches are skipped and do not loop forever
self.ae(find_matches(['abc'], parse_query('\\r x*')), [])
def test_current_match(self):
lines = ['one 17 here', 'nothing', '17 and 17']
query = parse_query('17')
matches = find_matches(lines, query)
search = ScrollbackSearch(query, compile_query(query), matches, total_lines=len(lines))
self.ae(len(search), 3)
self.ae(search.current_match, Match(0, 4, 6))
search.index = 2
self.ae(search.current_match, Match(2, 7, 9))
# The current match is the only one with its own color, and navigation
# moves that color along
spans = search.marker_spans(lines)
self.ae(spans['one 17 here'], ((4, 6, MATCH_COLOR),))
self.ae(spans['17 and 17'], ((0, 2, MATCH_COLOR), (7, 9, CURRENT_MATCH_COLOR)))
search.index = 1
self.ae(search.marker_spans(lines)['17 and 17'], ((0, 2, CURRENT_MATCH_COLOR), (7, 9, MATCH_COLOR)))
# Wrapping the index keeps exactly one current match selected
search.index = 4 % len(search.matches)
self.ae(sum(1 for found in search.marker_spans(lines).values() for span in found if span[2] == CURRENT_MATCH_COLOR), 1)
def test_scroll_offset(self):
self.ae(scroll_offset_for(Match(0, 0, 1), 100, 10), 90)
self.ae(scroll_offset_for(Match(50, 0, 1), 100, 10), 43)
self.ae(scroll_offset_for(Match(99, 0, 1), 100, 10), 0)
# No scrollback: the visible screen is always shown as is
self.ae(scroll_offset_for(Match(3, 0, 1), 5, 5), 0)
def test_performance_on_large_scrollback(self):
lines = [f'line {i} with some ordinary text' for i in range(10_000)]
for i in range(0, 10_000, 10):
lines[i] = 'needle ' + lines[i]
query = parse_query('needle')
start = time.monotonic()
matches = find_matches(lines, query)
elapsed = time.monotonic() - start
self.ae(len(matches), 1000)
self.assertLess(elapsed, 0.05, f'searching 10 000 lines took {elapsed * 1000:.1f} ms')
-145
View File
@@ -1,145 +0,0 @@
#!/usr/bin/env python
# License: GPL v3 Copyright: 2026, Kovid Goyal <kovid at kovidgoyal.net>
import json
import os
import shutil
import tempfile
from unittest.mock import patch
from kitty.config import load_config
from kitty.session import create_sessions, parse_session
from kitty.session_restore import (
MAX_STATE_SIZE,
discard_last_session,
load_last_session,
prune_missing_directories,
save_last_session,
state_path,
)
from kitty.utils import log_error
from .base import BaseTest
class TestSessionRestore(BaseTest):
def setUp(self) -> None:
super().setUp()
self.tdir = tempfile.mkdtemp()
self.env_patch = patch.dict(os.environ, {'XDG_STATE_HOME': self.tdir})
self.env_patch.start()
self.error_messages: list[str] = []
log_error.redirect = self.error_messages.append
def tearDown(self) -> None:
del log_error.redirect
self.env_patch.stop()
shutil.rmtree(self.tdir)
super().tearDown()
def write_state(self, data: bytes) -> None:
os.makedirs(os.path.dirname(state_path()), exist_ok=True)
with open(state_path(), 'wb') as f:
f.write(data)
def test_state_lives_in_the_xdg_state_directory(self) -> None:
self.ae(state_path(), os.path.join(self.tdir, 'kitty', 'last-session.json'))
def test_roundtrip(self) -> None:
session = 'new_tab work\nlayout tall\ncd /tmp\nlaunch --title editor\nlaunch'
self.assertTrue(save_last_session(session))
self.assertTrue(os.path.exists(state_path()))
self.ae(load_last_session(), session)
def test_nothing_is_saved_for_an_empty_session(self) -> None:
self.assertFalse(save_last_session(' \n'))
self.ae(load_last_session(), '')
def test_missing_state_is_not_an_error(self) -> None:
self.ae(load_last_session(), '')
self.ae(self.error_messages, [])
def test_too_large_state_is_neither_saved_nor_restored(self) -> None:
self.assertFalse(save_last_session('x' * (MAX_STATE_SIZE + 1)))
self.assertFalse(os.path.exists(state_path()))
self.write_state(json.dumps({'version': 1, 'session': 'x' * (MAX_STATE_SIZE + 1)}).encode())
self.ae(load_last_session(), '')
self.assertFalse(os.path.exists(state_path()))
self.assertTrue(self.error_messages)
def test_corrupt_state_is_discarded(self) -> None:
self.write_state(b'{"version": 1, "session": ')
self.ae(load_last_session(), '')
self.assertFalse(os.path.exists(state_path()))
self.assertTrue(any('cannot be read' in msg for msg in self.error_messages))
def test_newer_state_version_is_discarded(self) -> None:
self.write_state(json.dumps({'version': 99, 'session': 'launch'}).encode())
self.ae(load_last_session(), '')
self.assertFalse(os.path.exists(state_path()))
def test_missing_or_invalid_fields_are_discarded(self) -> None:
for data in ({}, {'version': 1}, {'session': 'launch'}, {'version': '1', 'session': 'launch'}, []):
self.write_state(json.dumps(data).encode())
self.ae(load_last_session(), '', data)
self.assertFalse(os.path.exists(state_path()), data)
self.assertFalse(os.path.exists(state_path()))
def test_discard_is_idempotent(self) -> None:
discard_last_session()
self.ae(self.error_messages, [])
def test_stale_directories_are_pruned(self) -> None:
missing = os.path.join(self.tdir, 'gone')
session = f'new_tab a\ncd {missing}\nlaunch\nnew_tab b\ncd {self.tdir}\nlaunch'
session, pruned = prune_missing_directories(session)
self.ae(pruned, 1)
self.assertNotIn(missing, session)
self.assertIn(f'cd {self.tdir}', session)
self.assertIn('new_tab b', session)
self.assertTrue(self.error_messages == []) # pruning itself does not log
def test_pruning_is_applied_when_loading(self) -> None:
missing = os.path.join(self.tdir, 'gone')
self.assertTrue(save_last_session(f'cd {missing}\nlaunch'))
self.ae(load_last_session(), 'launch')
self.assertTrue(any('no longer exist' in msg for msg in self.error_messages))
def test_saved_state_is_a_valid_session(self) -> None:
session = 'new_tab one\nlayout tall\nlaunch\nnew_tab two\nlaunch'
self.assertTrue(save_last_session(session))
opts = load_config()
sessions = tuple(parse_session(load_last_session(), opts, session_arg='last', session_path=state_path()))
self.ae(len(sessions), 1)
self.ae(sessions[0].session_name, 'last')
self.ae([t.name for t in sessions[0].tabs], ['one', 'two'])
def test_restore_is_explicit_on_the_command_line(self) -> None:
from kitty.cli import parse_args
self.assertTrue(save_last_session('launch'))
opts = load_config()
args, rest = parse_args(['--session', 'last'])
args.args = [] # type: ignore
self.ae(args.session, 'last')
self.ae(rest, [])
sessions = tuple(create_sessions(opts, args))
self.ae(len(sessions), 1)
self.ae(sessions[0].session_name, 'last')
self.ae(len(sessions[0].tabs[0].windows), 1)
def test_missing_state_falls_back_to_a_fresh_session(self) -> None:
from kitty.cli import parse_args
opts = load_config()
args, rest = parse_args(['--session', 'last'])
args.args = [] # type: ignore
sessions = tuple(create_sessions(opts, args))
self.ae(len(sessions), 1)
self.ae(sessions[0].session_name, '')
self.assertTrue(any('no saved session' in msg for msg in self.error_messages))
def test_restore_action_without_state_returns_false(self) -> None:
from kitty.session_restore import restore_last_session_into
self.assertFalse(restore_last_session_into(None)) # type: ignore
+2 -26
View File
@@ -11,26 +11,16 @@
# upstream package, hence provides/conflicts. # upstream package, hence provides/conflicts.
pkgname=fws-kitty pkgname=fws-kitty
# Fork version from the version file: it names the release and the package. pkgver=0.50.0
# The upstream kitty release built inside is tracked by _kittyver below.
pkgver=0.1.17
pkgrel=1 pkgrel=1
pkgdesc='Fast, feature-rich, GPU based terminal (FWS fork with the file-manager kitten)' pkgdesc='Fast, feature-rich, GPU based terminal (FWS fork with the file-manager kitten)'
arch=('x86_64' 'aarch64') arch=('x86_64' 'aarch64')
url='https://gitea.nocode-var.tech/FWS/FWS-Kitty' url='https://gitea.nocode-var.tech/FWS/FWS-Kitty'
license=('GPL-3.0-only') license=('GPL-3.0-only')
# Upstream kitty release shipped by this package. It is independent from pkgver
# and must match kitty/constants.py (checked by check-version.sh).
_kittyver=0.50.0
# Replace main with the tag or commit to ship once the release is cut. # Replace main with the tag or commit to ship once the release is cut.
_branch=main _branch=main
_repo='https://gitea.nocode-var.tech/FWS/FWS-Kitty.git' _repo='https://gitea.nocode-var.tech/FWS/FWS-Kitty.git'
# The CI sets FWS_SOURCE_REF=commit=<sha> so the package is built from the exact
# commit being released instead of whatever main points at by the time makepkg
# clones. A local build keeps following _branch.
_source_ref=${FWS_SOURCE_REF:-branch=$_branch}
depends=( depends=(
python harfbuzz zlib libpng lcms2 xxhash openssl python harfbuzz zlib libpng lcms2 xxhash openssl
@@ -38,9 +28,6 @@ depends=(
libx11 libxcb libxrandr libxinerama libxcursor libxi libxrender libx11 libxcb libxrandr libxinerama libxcursor libxi libxrender
libxkbcommon libxkbcommon-x11 mesa wayland dbus libxkbcommon libxkbcommon-x11 mesa wayland dbus
libcanberra systemd-libs libcanberra systemd-libs
# Arch ships these files in separate packages; shipping them here would
# make pacman abort on file conflicts with the installed split packages.
kitty-shell-integration kitty-terminfo
) )
makedepends=( makedepends=(
git go python pkgconf ncurses rsync which file simde shader-slang git go python pkgconf ncurses rsync which file simde shader-slang
@@ -52,13 +39,8 @@ optdepends=(
provides=('kitty') provides=('kitty')
conflicts=('kitty') conflicts=('kitty')
# The release publishes only the main package, so the separate debug package is
# built and thrown away. Skipping it also avoids makepkg running gdb-add-index
# over binaries that were already stripped, which only prints errors.
options=('!debug')
source=( source=(
"$pkgname::git+$_repo#$_source_ref" "$pkgname::git+$_repo#branch=$_branch"
"nerdfonts-symbols.tar.xz::https://github.com/ryanoasis/nerd-fonts/releases/download/v3.5.1/NerdFontsSymbolsOnly.tar.xz" "nerdfonts-symbols.tar.xz::https://github.com/ryanoasis/nerd-fonts/releases/download/v3.5.1/NerdFontsSymbolsOnly.tar.xz"
) )
sha256sums=('SKIP' '01172f37db8543edb102e5cb5c64101c9f4686630804d49b419aa07b23a69996') sha256sums=('SKIP' '01172f37db8543edb102e5cb5c64101c9f4686630804d49b419aa07b23a69996')
@@ -84,11 +66,5 @@ package() {
# kitty's linux-package target stages a full self-contained install, so # kitty's linux-package target stages a full self-contained install, so
# pointing --prefix at the package root is enough; no manual file copying. # pointing --prefix at the package root is enough; no manual file copying.
PATH="$srcdir/$pkgname/.docs-venv/bin:$PATH" python setup.py linux-package --prefix "$pkgdir/usr" PATH="$srcdir/$pkgname/.docs-venv/bin:$PATH" python setup.py linux-package --prefix "$pkgdir/usr"
# These paths are owned by kitty-shell-integration and kitty-terminfo on
# Arch. Remove them here so upgrading from upstream kitty does not fail
# with pacman file conflicts; the dependencies above provide them.
rm -rf "$pkgdir/usr/lib/kitty/shell-integration"
rm -f "$pkgdir/usr/share/terminfo/x/xterm-kitty"
rmdir --ignore-fail-on-non-empty "$pkgdir/usr/share/terminfo/x" "$pkgdir/usr/share/terminfo" 2>/dev/null || true
install -Dm644 LICENSE "$pkgdir/usr/share/licenses/$pkgname/LICENSE" install -Dm644 LICENSE "$pkgdir/usr/share/licenses/$pkgname/LICENSE"
} }
+5 -65
View File
@@ -5,11 +5,6 @@ prêt à être publié dans le dépôt officiel FWS. Le paquet s'appelle
`fws-kitty` et remplace `kitty` (`provides`/`conflicts`) : les deux ne peuvent `fws-kitty` et remplace `kitty` (`provides`/`conflicts`) : les deux ne peuvent
pas cohabiter, ils installent les mêmes binaires dans `/usr/bin`. pas cohabiter, ils installent les mêmes binaires dans `/usr/bin`.
L'intégration shell et le terminfo restent fournis par les paquets Arch
`kitty-shell-integration` et `kitty-terminfo`, dont `fws-kitty` dépend. Le
`PKGBUILD` retire ces fichiers de son propre paquet pour éviter les conflits
de fichiers lors du remplacement de `kitty`.
## Construire ## Construire
```sh ```sh
@@ -68,63 +63,7 @@ fonctionne pour héberger les fichiers, mais pacman a besoin d'URL stables pour
`fws-kitty.db.tar.gz` et les `.pkg.tar.zst`, ce qu'un simple dossier servi par `fws-kitty.db.tar.gz` et les `.pkg.tar.zst`, ce qu'un simple dossier servi par
nginx (ou des assets de release) fournit directement. nginx (ou des assets de release) fournit directement.
## Publication automatique Pour une publication automatique, il suffit d'enchaîner dans la CI :
Le fichier `version`, à la racine du dépôt, déclenche tout : un push sur `main`
qui le modifie lance `.gitea/workflows/package.yml` : lint, puis construction du
paquet avec ce `PKGBUILD` depuis le commit exact — c'est le seul build, les
`go vet`, tests et smoke test tournent sur cet arbre — avant de créer la
release Gitea `v<version>` (paquet + empreinte SHA-256 en pièces jointes) et
d'envoyer le paquet à `repo.laxacube.ch`.
Le workflow a besoin de deux secrets du dépôt :
| Secret | Usage |
| --- | --- |
| `RELEASE_TOKEN` | créer la release et y attacher les fichiers |
| `REPO_TOKEN` | `POST https://repo.laxacube.ch/api/packages` |
Sans `REPO_TOKEN`, la release est créée mais le dépôt pacman n'est pas mis à
jour (le workflow émet un avertissement). Pour reconstruire la même version du
fork, incrémentez `pkgrel` ici et lancez le workflow manuellement ; le paquet
`0.1.8-2` remplace le `0.1.8-1` dans la base `fws.db` reconstruite côté
serveur. Le `PKGBUILD` lit `FWS_SOURCE_REF` (`commit=<sha>` depuis la CI) pour
construire le commit publié plutôt que la tête de `main`.
Une version publiée n'est jamais réécrite : deux builds du même commit ne sont
pas identiques à l'octet près, et le CDN comme le cache pacman gardent le fichier
sous son nom, donc republier `0.1.8-1` avec un autre contenu donne des caches qui
désaccordent avec la base et pacman rejette le téléchargement (`paquet non valide
ou corrompu`). Le workflow s'arrête donc sans republier quand le dépôt sert déjà
ce nom de paquet (relancer une release est sans effet), et demande d'incrémenter
`pkgrel` pour publier un build différent.
Après l'envoi, il relit aussi le paquet servi et compare son `sha256` à celui du
build, pour ne pas annoncer une publication que les clients ne peuvent pas
installer. Le fichier met quelques secondes à être routé après l'upload : il est
retenté pendant deux minutes, et une empreinte différente échoue immédiatement.
`pkgver` est la version du fork FWS (fichier `version` à la racine), pas celle
de kitty : la version amont embarquée est dans `_kittyver`.
`packaging/check-version.sh` vérifie avant le build que `version` et `pkgver`
concordent avec la version compilée dans `tools/cli/help.go` et
`kitty/launcher/main.c`, et que `_kittyver` correspond à `kitty/constants.py`.
### Runner
Les jobs tournent sur un runner Arch auto-hébergé (label `arch-host`).
`packaging/install-ci-deps.sh` installe ce qui manque, mais `pacman` a besoin
de root : soit le runner a un sudo sans mot de passe pour `pacman`, soit les
paquets sont préinstallés une fois sur la machine :
```sh
sudo pacman -S --needed go rsync ruff shader-slang libcanberra simde \
wayland-protocols wayland-utils kitty-shell-integration kitty-terminfo
```
Une fois installés, le script est un no-op et les jobs n'utilisent plus de
privilège.
Pour publier à la main :
```sh ```sh
makepkg -f --nodeps # ou -s avec un utilisateur autorisé à pacman makepkg -f --nodeps # ou -s avec un utilisateur autorisé à pacman
@@ -132,6 +71,7 @@ repo-add repo/fws-kitty.db.tar.gz fws-kitty-*.pkg.tar.zst
# puis copier repo/ vers le serveur # puis copier repo/ vers le serveur
``` ```
Le paquet ne contient pas les fichiers appartenant à `kitty-shell-integration` Si le dépôt doit aussi fournir `kitty-terminfo` et l'intégration shell aux
et `kitty-terminfo`. Ces paquets restent nécessaires pour l'utilisation de serveurs SSH, ces fichiers peuvent être découpés en paquets séparés : la
kitty et sont donc déclarés en dépendances. documentation de kitty (`docs/build.rst`, section « Notes pour les
empaqueteurs ») décrit la répartition.
-55
View File
@@ -1,55 +0,0 @@
#!/bin/sh
# The version file is the single source of truth for a release: it triggers the
# packaging workflow and names the tag, the Gitea release and the Arch package.
# It tracks the FWS fork version, which is independent from the upstream kitty
# release shipped inside the package. Both numbers are duplicated where the
# build reads them, so this script checks they still agree and prints the
# release version for the workflows to reuse:
#
# version="$(packaging/check-version.sh)"
#
# It runs on the CI runner and locally, before any build.
set -eu
root=$(CDPATH='' cd -- "$(dirname -- "$0")/.." && pwd)
fail() {
echo "::error file=$1::$2"
exit 1
}
version=$(tr -d '[:space:]' < "$root/version")
case "$version" in
''|*[!0-9.]*|.*|*..*|*.)
fail version "expected MAJOR.MINOR.PATCH, got '$version'"
;;
esac
if [ "$(printf '%s' "$version" | awk -F. '{print NF}')" -ne 3 ]; then
fail version "expected MAJOR.MINOR.PATCH, got '$version'"
fi
# makepkg names the package from pkgver, so an out-of-date PKGBUILD would
# publish a package whose name does not match its release.
pkgver=$(sed -n 's/^pkgver=//p' "$root/packaging/PKGBUILD" | head -n 1)
if [ "$pkgver" != "$version" ]; then
fail packaging/PKGBUILD "pkgver is '$pkgver' but the version file says '$version'"
fi
# The upstream kitty release follows kitty, not the fork: it lives in its own
# variable and must keep matching the constant kitty compiles into the binaries.
kitty_version=$(sed -n 's/^_kittyver=//p' "$root/packaging/PKGBUILD" | head -n 1)
constants=$(sed -n 's/^version: Version = Version(\([0-9]*\), \([0-9]*\), \([0-9]*\)).*/\1.\2.\3/p' "$root/kitty/constants.py" | head -n 1)
if [ "$constants" != "$kitty_version" ]; then
fail kitty/constants.py "kitty reports '$constants' but _kittyver in the PKGBUILD says '$kitty_version'"
fi
# The fork version is hard-coded in both front-ends, so bumping only the version
# file would ship binaries announcing the previous release.
for f in tools/cli/help.go kitty/launcher/main.c; do
if ! grep -qF "$version" "$root/$f"; then
fail "$f" "the fork version '$version' is not set in this file"
fi
done
printf '%s\n' "$version"
-44
View File
@@ -1,44 +0,0 @@
#!/bin/sh
# Install on the Arch CI runner everything the linter, ./dev.sh build and
# makepkg need. Idempotent: nothing is handed to pacman when it is already
# installed, and sudo is only used when something is actually missing.
#
# The runner user needs passwordless sudo for pacman the first time; once the
# packages are there, the script is a no-op and no privilege is required.
set -eu
packages="git go python pkgconf ncurses rsync which file jq curl nodejs ruff \
harfbuzz zlib libpng lcms2 xxhash openssl shader-slang pixman cairo freetype2 \
fontconfig libcanberra systemd-libs simde libx11 libxcb libxrandr libxinerama \
libxcursor libxi libxrender xorgproto libxkbcommon libxkbcommon-x11 mesa dbus \
wayland wayland-protocols wayland-utils tar xz kitty-shell-integration \
kitty-terminfo"
missing=""
for package in $packages; do
if ! pacman -Q "$package" > /dev/null 2>&1; then
missing="$missing $package"
fi
done
# base-devel is a group, so verbose queries do not report it as a package.
for tool in gcc make fakeroot; do
if ! command -v "$tool" > /dev/null 2>&1; then
missing="$missing base-devel"
break
fi
done
if [ -z "$missing" ]; then
echo 'All the build dependencies are already installed.'
exit 0
fi
echo "Installing:$missing"
# pacman refuses to run without a terminal prompt for the password when the
# runner user has no NOPASSWD rule; fail with the list instead of hanging.
if ! sudo -n pacman -S --needed --noconfirm $missing; then
echo "::error::could not install:$missing"
echo '::error::give the runner user passwordless sudo for pacman or preinstall these packages.'
exit 1
fi
+1 -32
View File
@@ -213,10 +213,6 @@ _ksi_main() {
builtin printf "\e]7;kitty-shell-cwd://%s%s\a" "$HOSTNAME" "$PWD" builtin printf "\e]7;kitty-shell-cwd://%s%s\a" "$HOSTNAME" "$PWD"
fi fi
fi fi
if [[ -n "${_ksi_cwd_sync_file:-}" ]]; then
_ksi_cwd_sync_apply
fi
} }
if [[ "${_ksi_prompt[cursor]}" == "y" ]]; then if [[ "${_ksi_prompt[cursor]}" == "y" ]]; then
@@ -269,35 +265,9 @@ _ksi_main() {
_ksi_prompt[ps2]+="\[\e]133;A;k=s\a\]" _ksi_prompt[ps2]+="\[\e]133;A;k=s\a\]"
fi fi
# Optional working directory sync with the file manager panel (sync_cwd).
# The panel publishes the directory it wants in <dir>/<window id>.set and we
# apply it at prompt time instead of typing a cd into the terminal: the
# command stays out of the history and a half typed multi-line command is
# not submitted. We publish our own directory the same way so that the panel
# can follow a cd made here.
if [[ -n "$KITTY_CWD_SYNC_DIR" && -n "$KITTY_WINDOW_ID" && -d "$KITTY_CWD_SYNC_DIR" ]]; then
_ksi_cwd_sync_file="$KITTY_CWD_SYNC_DIR/$KITTY_WINDOW_ID"
_ksi_cwd_sync_publish() {
builtin printf '%s' "$PWD" > "$_ksi_cwd_sync_file" 2> /dev/null
builtin return 0
}
_ksi_cwd_sync_apply() {
builtin local ret=$? target
if [[ -f "$_ksi_cwd_sync_file.set" ]]; then
IFS= builtin read -r target < "$_ksi_cwd_sync_file.set"
builtin command rm -f -- "$_ksi_cwd_sync_file.set"
if [[ -n "$target" && -d "$target" ]]; then
builtin cd -- "$target"
fi
fi
_ksi_cwd_sync_publish
builtin return $ret
}
_ksi_cwd_sync_publish
fi
builtin alias edit-in-kitty="kitten edit-in-kitty" builtin alias edit-in-kitty="kitten edit-in-kitty"
if [[ "${_ksi_prompt[complete]}" == "y" ]]; then if [[ "${_ksi_prompt[complete]}" == "y" ]]; then
_ksi_completions() { _ksi_completions() {
builtin local src builtin local src
@@ -345,7 +315,6 @@ _ksi_main() {
# from the shell # from the shell
builtin local pc builtin local pc
pc='builtin declare -F _ksi_prompt_command > /dev/null 2> /dev/null && _ksi_prompt_command' pc='builtin declare -F _ksi_prompt_command > /dev/null 2> /dev/null && _ksi_prompt_command'
if [[ -n "${_ksi_cwd_sync_file:-}" ]]; then pc="$pc; _ksi_cwd_sync_apply"; fi
if [[ -z "${PROMPT_COMMAND[*]}" ]]; then if [[ -z "${PROMPT_COMMAND[*]}" ]]; then
PROMPT_COMMAND=([0]="$pc") PROMPT_COMMAND=([0]="$pc")
elif [[ $(builtin declare -p PROMPT_COMMAND 2> /dev/null) =~ 'declare -a PROMPT_COMMAND' ]]; then elif [[ $(builtin declare -p PROMPT_COMMAND 2> /dev/null) =~ 'declare -a PROMPT_COMMAND' ]]; then
@@ -137,28 +137,6 @@ function __ksi_schedule --on-event fish_prompt -d "Setup kitty integration after
__update_cwd_osc __update_cwd_osc
end end
# Optional working directory sync with the file manager panel (sync_cwd).
# The panel publishes the directory it wants in <dir>/<window id>.set and we
# apply it at prompt time instead of typing a cd into the terminal, see the
# bash integration for the rationale.
if set -q KITTY_CWD_SYNC_DIR; and set -q KITTY_WINDOW_ID; and test -d "$KITTY_CWD_SYNC_DIR"
function __ksi_cwd_sync_publish --on-event fish_prompt -d "Publish the working directory for the file manager panel"
printf '%s' "$PWD" > "$KITTY_CWD_SYNC_DIR/$KITTY_WINDOW_ID" 2> /dev/null
end
function __ksi_cwd_sync_apply --on-event fish_prompt -d "Apply a directory chosen in the file manager panel"
set --local file "$KITTY_CWD_SYNC_DIR/$KITTY_WINDOW_ID.set"
if test -f "$file"
set --local target (cat "$file")
rm -f -- "$file"
if test -n "$target" -a -d "$target"
builtin cd -- "$target"
end
end
__ksi_cwd_sync_publish
end
__ksi_cwd_sync_publish
end
# Note that neither alias nor function is recursive in fish so if the user defines an alias/function # Note that neither alias nor function is recursive in fish so if the user defines an alias/function
# for sudo/run0 it will be clobbered by us, so only install these if they are not already functions # for sudo/run0 it will be clobbered by us, so only install these if they are not already functions
if not contains "no-sudo" $_ksi if not contains "no-sudo" $_ksi
-25
View File
@@ -246,31 +246,6 @@ _ksi_deferred_init() {
_ksi_report_pwd _ksi_report_pwd
fi fi
# Optional working directory sync with the file manager panel (sync_cwd).
# The panel publishes the directory it wants in <dir>/<window id>.set and we
# apply it at prompt time instead of typing a cd into the terminal, see the
# bash integration for the rationale.
if [[ -n $KITTY_CWD_SYNC_DIR && -n $KITTY_WINDOW_ID && -d $KITTY_CWD_SYNC_DIR ]]; then
builtin typeset -g _ksi_cwd_sync_file="$KITTY_CWD_SYNC_DIR/$KITTY_WINDOW_ID"
_ksi_cwd_sync_publish() { builtin print -rn -- "$PWD" >| "$_ksi_cwd_sync_file" 2> /dev/null; }
_ksi_cwd_sync_apply() {
builtin local -i ret=$?
builtin local target
if [[ -f "$_ksi_cwd_sync_file.set" ]]; then
IFS= builtin read -r target < "$_ksi_cwd_sync_file.set"
builtin command rm -f -- "$_ksi_cwd_sync_file.set"
if [[ -n $target && -d $target ]]; then
builtin cd -- "$target"
fi
fi
_ksi_cwd_sync_publish
builtin return ret
}
_ksi_cwd_sync_publish
precmd_functions+=(_ksi_cwd_sync_apply)
chpwd_functions+=(_ksi_cwd_sync_publish)
fi
# Enable terminal title changes. # Enable terminal title changes.
if (( ! opt[(Ie)no-title] )); then if (( ! opt[(Ie)no-title] )); then
# We don't use `print -P` because it depends on prompt options, which # We don't use `print -P` because it depends on prompt options, which
+1 -2
View File
@@ -30,8 +30,7 @@ func ShowError(err error) {
} }
func (self *Command) version_string(formatter *markup.Context) string { func (self *Command) version_string(formatter *markup.Context) string {
return fmt.Sprintln(formatter.Italic(self.CommandStringForUsage()), formatter.Opt(kitty.VersionString+kitty.VersionSuffix), "created by", formatter.Title("Kovid Goyal")) + return fmt.Sprintln(formatter.Italic(self.CommandStringForUsage()), formatter.Opt(kitty.VersionString+kitty.VersionSuffix), "created by", formatter.Title("Kovid Goyal"))
fmt.Sprintln(formatter.Italic("fws-kitty"), formatter.Opt("0.1.17"), "by", formatter.Title("BlackAngelTV"))
} }
func (self *Command) ShowVersion() { func (self *Command) ShowVersion() {
+5 -21
View File
@@ -97,21 +97,6 @@ func shell_loop(rl *readline.Readline, kill_if_signaled bool) (int, error) {
return 0, nil return 0, nil
} }
// launch_shortcuts_panel opens the searchable keybinding reference in a dock,
// next to the terminal, instead of taking over the shell window.
func launch_shortcuts_panel() int {
kitty := utils.KittyExe()
if kitty == "" {
kitty = "kitty"
}
root := cli.NewRootCommand()
EntryPoint(root)
return root.ExecArgs([]string{
"kitten", "@", "launch", "--type=window-dock", "--dock-edge=left", "--dock-size=60",
kitty, "+kitten", "help",
})
}
func show_basic_help() { func show_basic_help() {
output := strings.Builder{} output := strings.Builder{}
fmt.Fprintln(&output, "Control kitty by sending it commands.") fmt.Fprintln(&output, "Control kitty by sending it commands.")
@@ -125,7 +110,7 @@ func show_basic_help() {
} }
} }
fmt.Fprintln(&output, " ", formatter.Green("help")) fmt.Fprintln(&output, " ", formatter.Green("help"))
fmt.Fprintln(&output, " ", "Show keyboard shortcuts") fmt.Fprintln(&output, " ", "Show this help")
fmt.Fprintln(&output, " ", formatter.Green("exit")) fmt.Fprintln(&output, " ", formatter.Green("exit"))
fmt.Fprintln(&output, " ", "Exit this shell") fmt.Fprintln(&output, " ", "Exit this shell")
cli.ShowHelpInPager(output.String()) cli.ShowHelpInPager(output.String())
@@ -151,14 +136,14 @@ func exec_command(at_root_command *cli.Command, rl *readline.Readline, cmdline s
hi.ExitCode = 0 hi.ExitCode = 0
defer rl.AddHistoryItem(hi) defer rl.AddHistoryItem(hi)
if len(parsed_cmdline) == 1 { if len(parsed_cmdline) == 1 {
hi.ExitCode = launch_shortcuts_panel() show_basic_help()
return true return true
} }
switch parsed_cmdline[1] { switch parsed_cmdline[1] {
case "exit": case "exit":
fmt.Println("Exit this shell") fmt.Println("Exit this shell")
case "help": case "help":
fmt.Println("Show keyboard shortcuts") fmt.Println("Show help")
default: default:
sc := at_root_command.FindSubCommand(parsed_cmdline[1]) sc := at_root_command.FindSubCommand(parsed_cmdline[1])
if sc == nil { if sc == nil {
@@ -205,7 +190,7 @@ func completions(before_cursor, after_cursor string) (ans *cli.Completions) {
} }
x.ShortDescription = desc x.ShortDescription = desc
} }
add_sc("help", "Show keyboard shortcuts") add_sc("help", "Show help")
add_sc("exit", "Exit the kitty shell") add_sc("exit", "Exit the kitty shell")
root.Validate() root.Validate()
ans = root.GetCompletions(argv, nil) ans = root.GetCompletions(argv, nil)
@@ -221,8 +206,7 @@ func shell_main(cmd *cli.Command, args []string) (int, error) {
running_shell = true running_shell = true
formatter = markup.New(true) formatter = markup.New(true)
fmt.Println("Welcome to the kitty shell!") fmt.Println("Welcome to the kitty shell!")
fmt.Println("Use", formatter.Green("Ctrl+Shift+H"), "or", formatter.Green("help"), "for the keyboard shortcuts panel.") fmt.Println("Use", formatter.Green("help"), "for assistance or", formatter.Green("exit"), "to quit.")
fmt.Println("Use", formatter.Green("help <command>"), "for a command's help, or", formatter.Green("exit"), "to quit.")
if atwid := os.Getenv("KITTY_SHELL_ACTIVE_WINDOW_ID"); atwid != "" { if atwid := os.Getenv("KITTY_SHELL_ACTIVE_WINDOW_ID"); atwid != "" {
amsg := "Previously active window id: " + atwid amsg := "Previously active window id: " + atwid
os.Unsetenv("KITTY_SHELL_ACTIVE_WINDOW_ID") os.Unsetenv("KITTY_SHELL_ACTIVE_WINDOW_ID")
-1
View File
@@ -1 +0,0 @@
0.1.17