Compare commits
127
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5a1ba595f1
|
||
|
|
a142e0b596
|
||
|
|
ee3f064886
|
||
|
|
e39f938a39 | ||
|
|
408f16f798
|
||
|
|
84f5500444 | ||
|
|
43d01ab87e
|
||
|
|
42c097c69a
|
||
|
|
1b9e076139 | ||
|
|
e1cce67221
|
||
|
|
406bd726e2
|
||
|
|
271babc8f1 | ||
|
|
6e60b16e36
|
||
|
|
365873b9bb
|
||
|
|
b994ccffce | ||
|
|
474f1c0568
|
||
|
|
17462f5198
|
||
|
|
b036fb352e | ||
|
|
f76eccc169
|
||
|
|
801b4a2d89
|
||
|
|
d83fbc71e3 | ||
|
|
cbee630d4c
|
||
|
|
4df542f590
|
||
|
|
b406be9394 | ||
|
|
4ca4a516ae
|
||
|
|
f616651c49
|
||
|
|
1bd822b9e5
|
||
|
|
ce9f7ab974
|
||
|
|
603ef78a6e
|
||
|
|
f2f026c748
|
||
|
|
ec42571be5
|
||
|
|
dea1771fe5
|
||
|
|
0cce80a6c5
|
||
|
|
70befe3802
|
||
|
|
a3d0fd38b7
|
||
|
|
25840c6ce1
|
||
|
|
af032e3d87
|
||
|
|
533cc3873d
|
||
|
|
bd22a8c5f3
|
||
|
|
576189533c
|
||
|
|
5f232ff99c
|
||
|
|
1d6911c476
|
||
|
|
05621aebd2
|
||
|
|
aa1fff96b4
|
||
|
|
f38246f71d
|
||
|
|
54934eb03a
|
||
|
|
86428e1863
|
||
|
|
7b64da8a38
|
||
|
|
afc53e370d
|
||
|
|
dc13716431
|
||
|
|
58fc9d1aa3
|
||
|
|
c1d4ca8c2d
|
||
|
|
7c17b5c0ce
|
||
|
|
f204f77b40
|
||
|
|
ab0533b825
|
||
|
|
d5f2847ff5
|
||
|
|
81df6f2d3a
|
||
|
|
45a16ea61c
|
||
|
|
8482515412
|
||
|
|
4e3d6b97dc
|
||
|
|
13c49c89aa
|
||
|
|
d373fe5df8
|
||
|
|
263607ab47
|
||
|
|
d866fae523
|
||
|
|
7839f666d5
|
||
|
|
9512d8a417
|
||
|
|
38ec8c86d7
|
||
|
|
ea4faeb5ac
|
||
|
|
1b0f5faf6a
|
||
|
|
9bacd745c2
|
||
|
|
15bab74943
|
||
|
|
44b9aa166e
|
||
|
|
665f9d5f2c
|
||
|
|
831852a89f
|
||
|
|
f74d33597e
|
||
|
|
b1b26803cc
|
||
|
|
fb19c04798
|
||
|
|
205f01673b
|
||
|
|
ef5301a0bb
|
||
|
|
a2629aa4d9
|
||
|
|
36c4221b3f
|
||
|
|
d0c014d066
|
||
|
|
9f2749c529
|
||
|
|
d91a79e361
|
||
|
|
85f481b457
|
||
|
|
49cbc34ff2
|
||
|
|
2f127f05af
|
||
|
|
98b73edbcb
|
||
|
|
f896d75211
|
||
|
|
598030025b
|
||
|
|
343c7e8aeb
|
||
|
|
b691050719
|
||
|
|
d6bdffca10
|
||
|
|
8f8d2526ab
|
||
|
|
8708aa4101
|
||
|
|
3791cdc024
|
||
|
|
5d2e28b144
|
||
|
|
e7e4e849eb
|
||
|
|
1b330bcf81
|
||
|
|
f16ed6cbfe
|
||
|
|
d6b4f8b2a2
|
||
|
|
3625e55a43
|
||
|
|
a3a68399c5
|
||
|
|
5d81de162d
|
||
|
|
38afa54ad9
|
||
|
|
a8129b1d5d
|
||
|
|
0a15964b3e
|
||
|
|
d6b19f026b
|
||
|
|
ee7439ef11
|
||
|
|
953076b510
|
||
|
|
1cfe7217f9
|
||
|
|
9c1bf4d84f
|
||
|
|
93055004a9
|
||
|
|
4fb1402d9e
|
||
|
|
a12a05e666
|
||
|
|
4b59b3a375
|
||
|
|
86982b79be
|
||
|
|
fb87a7306f
|
||
|
|
01c1531119
|
||
|
|
4d10615cc4
|
||
|
|
154e91b906
|
||
|
|
5871baa33a
|
||
|
|
5c50bc4898
|
||
|
|
fc74f8a9a1
|
||
|
|
3769c5d08d
|
||
|
|
3f23d6e065
|
||
|
|
3d174c45a4
|
No files matched your search
@@ -1,3 +1,8 @@
|
||||
# kitty only builds and runs on Linux and macOS, so line endings are kept as LF
|
||||
# in the repository and in the working tree on every platform. Without this,
|
||||
# CRLF checkouts break dev.sh, the Makefile and anything else run by a shell.
|
||||
* text=auto eol=lf
|
||||
|
||||
kitty/terminfo.h linguist-generated=true
|
||||
terminfo/kitty.termcap linguist-generated=true
|
||||
terminfo/kitty.terminfo linguist-generated=true
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
# 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
|
||||
@@ -0,0 +1,252 @@
|
||||
# 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
|
||||
@@ -1,4 +0,0 @@
|
||||
github: kovidgoyal
|
||||
patreon: kovidgoyal
|
||||
liberapay: kovidgoyal
|
||||
custom: https://sw.kovidgoyal.net/kitty/support.html
|
||||
@@ -1,32 +0,0 @@
|
||||
---
|
||||
name: Bug report
|
||||
about: Create a bug report
|
||||
title: ''
|
||||
labels: bug
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
**Describe the bug**
|
||||
A clear and concise description of what the bug is.
|
||||
|
||||
**To Reproduce**
|
||||
Steps to reproduce the behavior:
|
||||
1. XXX
|
||||
2. YYY
|
||||
3. ZZZ
|
||||
4. See error
|
||||
|
||||
**Screenshots**
|
||||
If applicable, add screenshots to help explain your problem.
|
||||
|
||||
**Environment details**
|
||||
```
|
||||
Press Ctrl+Shift+F6 (cmd+option+comma on macOS) in kitty, to copy debug output about kitty and its
|
||||
configuration to the clipboard and paste it here.
|
||||
|
||||
On older versions of kitty, run kitty --debug-config instead
|
||||
```
|
||||
|
||||
**Additional context**
|
||||
Try to reproduce the problem with `kitty --config NONE` if you cannot then post a minimal kitty.conf that reproduces the problem. If the problem involves interaction with some other terminal program post a minimal config for that program to reproduce the problem as well.
|
||||
@@ -1,20 +0,0 @@
|
||||
---
|
||||
name: Feature request
|
||||
about: Suggest an idea for this project
|
||||
title: ''
|
||||
labels: enhancement
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
**Is your feature request related to a problem? Please describe.**
|
||||
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
|
||||
|
||||
**Describe the solution you'd like**
|
||||
A clear and concise description of what you want to happen.
|
||||
|
||||
**Describe alternatives you've considered**
|
||||
A clear and concise description of any alternative solutions or features you've considered.
|
||||
|
||||
**Additional context**
|
||||
Add any other context or screenshots about the feature request here.
|
||||
@@ -1,35 +0,0 @@
|
||||
Before implementing any code changes or responding to a request, run the
|
||||
following command:
|
||||
|
||||
python3 .github/workflows/ci.py build
|
||||
|
||||
This will download needed dependencies, then create all generated files
|
||||
and build the project, making it ready for inspection.
|
||||
|
||||
# Repository Build & Test Instructions
|
||||
|
||||
## Build Procedures
|
||||
- **Build command:** Run `./dev.sh build` to build the project
|
||||
- Run `gen/config.py` to update generated config parsing code for both kitty
|
||||
and kitten. The `gen/go_code.py` generator is run automatically by the build
|
||||
command to keep generated Go code files up to date.
|
||||
- To build individual kittens use the build command above **do not** try to run go build
|
||||
yourself.
|
||||
|
||||
Once a build is done, the kitty and kitten binaries will be in the `kitty/launcher` directory.
|
||||
Note that the kitty binary can run python files using `kitty +launch file.py`.
|
||||
When it does so the kitty fast_data_types module is available to the python
|
||||
code.
|
||||
|
||||
## Test Procedures
|
||||
- To run the complete test suite, run `./test.py`
|
||||
- To run a specific test, run `./test.py test_name` where `test_name` is the name of the test without the
|
||||
leading `test_` for Python tests and without the leading `Test` for Go tests.
|
||||
- Do not use go test or ./setup.py test to run tests
|
||||
|
||||
## PR guidance
|
||||
When creating a pull request, if the changes in the pull request are user
|
||||
visible compared to the previous kitty release, add an entry in the file docs/changelog.rst
|
||||
describing the change. If the changes include changes to Go code, run gofmt on
|
||||
the changed Go files to ensure they are formatted correctly, before submitting
|
||||
your changes.
|
||||
@@ -1,27 +0,0 @@
|
||||
# To get started with Dependabot version updates, you'll need to specify which
|
||||
# package ecosystems to update and where the package manifests are located.
|
||||
# Please see the documentation for all configuration options:
|
||||
# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates
|
||||
|
||||
version: 2
|
||||
updates:
|
||||
- package-ecosystem: "gomod" # See documentation for possible values
|
||||
directory: "/" # Location of package manifests
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
groups:
|
||||
all-go-deps:
|
||||
patterns:
|
||||
- "*" # group all non-security update PRs
|
||||
cooldown:
|
||||
default-days: 7
|
||||
- package-ecosystem: "github-actions"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
groups:
|
||||
actions:
|
||||
patterns:
|
||||
- "*"
|
||||
cooldown:
|
||||
default-days: 7
|
||||
@@ -1,378 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
# vim:fileencoding=utf-8
|
||||
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
import glob
|
||||
import io
|
||||
import json
|
||||
import lzma
|
||||
import os
|
||||
import platform
|
||||
import shlex
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tarfile
|
||||
import time
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
BUNDLE_URL = 'https://download.calibre-ebook.com/ci/kitty/{}-64.tar.xz'
|
||||
FONTS_URL = 'https://download.calibre-ebook.com/ci/fonts.tar.xz'
|
||||
NERD_URL = 'https://github.com/ryanoasis/nerd-fonts/releases/latest/download/NerdFontsSymbolsOnly.tar.xz'
|
||||
is_bundle = os.environ.get('KITTY_BUNDLE') == '1'
|
||||
is_codeql = os.environ.get('KITTY_CODEQL') == '1'
|
||||
is_macos = 'darwin' in sys.platform.lower()
|
||||
running_under_sanitizer = os.environ.get('KITTY_SANITIZE') == '1'
|
||||
SW = ''
|
||||
SLANG_INSTALL_DIR = '/tmp/slang'
|
||||
|
||||
|
||||
def do_print_crash_reports() -> None:
|
||||
sys.stdout.flush()
|
||||
sys.stderr.flush()
|
||||
time.sleep(2)
|
||||
print('Printing available crash reports...')
|
||||
if is_macos:
|
||||
end_time = time.monotonic() + 90
|
||||
while time.monotonic() < end_time:
|
||||
time.sleep(1)
|
||||
items = glob.glob(os.path.join(os.path.expanduser('~/Library/Logs/DiagnosticReports'), 'kitty-*.ips'))
|
||||
if items:
|
||||
break
|
||||
if items:
|
||||
time.sleep(1)
|
||||
print(os.path.basename(items[0]))
|
||||
sdir = os.path.dirname(os.path.abspath(__file__))
|
||||
subprocess.check_call([sys.executable, os.path.join(sdir, 'macos_crash_report.py'), items[0]])
|
||||
else:
|
||||
run('sh -c "echo bt | coredumpctl debug"')
|
||||
print(flush=True)
|
||||
|
||||
|
||||
def run(*a: str, print_crash_reports: bool = False) -> None:
|
||||
if len(a) == 1:
|
||||
a = tuple(shlex.split(a[0]))
|
||||
cmd = ' '.join(map(shlex.quote, a))
|
||||
print(cmd)
|
||||
sys.stdout.flush()
|
||||
ret = subprocess.Popen(a).wait()
|
||||
if ret != 0:
|
||||
if ret < 0:
|
||||
import signal
|
||||
|
||||
try:
|
||||
sig = signal.Signals(-ret)
|
||||
except ValueError:
|
||||
pass
|
||||
else:
|
||||
if print_crash_reports:
|
||||
do_print_crash_reports()
|
||||
raise SystemExit(f'The following process was killed by signal: {sig.name}:\n{cmd}')
|
||||
raise SystemExit(f'The following process failed with exit code: {ret}:\n{cmd}')
|
||||
|
||||
|
||||
def download_with_retry(url: str | Request, count: int = 5) -> bytes:
|
||||
for i in range(count):
|
||||
try:
|
||||
print('Downloading', getattr(url, 'full_url', url), flush=True)
|
||||
with urlopen(url) as f:
|
||||
ans: bytes = f.read()
|
||||
return ans
|
||||
except Exception as err:
|
||||
if getattr(err, 'code', -1) == 403:
|
||||
raise
|
||||
if i >= count - 1:
|
||||
raise
|
||||
print(f'Download failed with error {err} retrying...', file=sys.stderr)
|
||||
time.sleep(1)
|
||||
return b''
|
||||
|
||||
|
||||
def install_fonts() -> None:
|
||||
data = download_with_retry(FONTS_URL)
|
||||
fonts_dir = os.path.expanduser('~/Library/Fonts' if is_macos else '~/.local/share/fonts')
|
||||
os.makedirs(fonts_dir, exist_ok=True)
|
||||
with tarfile.open(fileobj=io.BytesIO(data), mode='r:xz') as tf:
|
||||
try:
|
||||
tf.extractall(fonts_dir, filter='fully_trusted')
|
||||
except TypeError:
|
||||
tf.extractall(fonts_dir)
|
||||
data = download_with_retry(NERD_URL)
|
||||
with tarfile.open(fileobj=io.BytesIO(data), mode='r:xz') as tf:
|
||||
try:
|
||||
tf.extractall(fonts_dir, filter='fully_trusted')
|
||||
except TypeError:
|
||||
tf.extractall(fonts_dir)
|
||||
|
||||
|
||||
def install_slang_compiler() -> None:
|
||||
os_name = 'macos' if is_macos else 'linux'
|
||||
machine = platform.machine().lower()
|
||||
arch = 'aarch64' if machine in ('aarch64', 'arm64') else 'x86_64'
|
||||
|
||||
with open('bypy/sources.json') as f:
|
||||
data = json.loads(f.read())
|
||||
for dep in data:
|
||||
if dep['name'].startswith('slang '):
|
||||
version = dep['name'].split()[-1]
|
||||
break
|
||||
url = f'https://github.com/shader-slang/slang/releases/download/v{version}/slang-{version}-{os_name}-{arch}.tar.gz'
|
||||
install_dir = SLANG_INSTALL_DIR
|
||||
os.makedirs(install_dir, exist_ok=True)
|
||||
data = download_with_retry(url)
|
||||
with tarfile.open(fileobj=io.BytesIO(data), mode='r:gz') as tf:
|
||||
try:
|
||||
tf.extractall(install_dir, filter='fully_trusted')
|
||||
except TypeError:
|
||||
# filter parameter not supported on older Python versions
|
||||
tf.extractall(install_dir)
|
||||
|
||||
pc_dir = os.path.join(install_dir, 'lib', 'pkgconfig')
|
||||
pp = os.environ.get('PKG_CONFIG_PATH', '')
|
||||
os.environ['PKG_CONFIG_PATH'] = f'{pc_dir}:{pp}' if pp else pc_dir
|
||||
|
||||
|
||||
def install_deps() -> None:
|
||||
print('Installing kitty dependencies...')
|
||||
sys.stdout.flush()
|
||||
if is_macos:
|
||||
if not is_codeql: # for some reason brew fails on CodeQL we dont need it anyway
|
||||
items = [x.split()[1].strip('"') for x in open('Brewfile').readlines() if x.strip().startswith('brew ')]
|
||||
openssl = 'openssl'
|
||||
items.remove('go') # already installed by ci.yml
|
||||
import ssl
|
||||
|
||||
if ssl.OPENSSL_VERSION_INFO[0] == 1:
|
||||
openssl += '@1.1'
|
||||
run('brew', 'install', 'fish', openssl, *items)
|
||||
else:
|
||||
run('sudo apt-get update')
|
||||
run(
|
||||
'sudo apt-get install -y --fix-missing libgl1-mesa-dev libxi-dev libxrandr-dev libxinerama-dev ca-certificates'
|
||||
' libxcursor-dev libxcb-xkb-dev libdbus-1-dev libxkbcommon-dev libharfbuzz-dev libx11-xcb-dev zsh'
|
||||
' libpng-dev liblcms2-dev libfontconfig-dev libxkbcommon-x11-dev libcanberra-dev libxxhash-dev uuid-dev'
|
||||
' libsimde-dev libsystemd-dev libcairo2-dev zsh bash dash systemd-coredump gdb'
|
||||
' libwayland-dev wayland-protocols glslang-tools'
|
||||
)
|
||||
# for some reason these directories are world writable which causes zsh
|
||||
# compinit to break
|
||||
run('sudo chmod -R og-w /usr/share/zsh')
|
||||
if is_bundle:
|
||||
install_bundle()
|
||||
else:
|
||||
cmd = 'python3 -m pip install Pillow pygments'
|
||||
if sys.version_info[:2] < (3, 7):
|
||||
cmd += ' importlib-resources dataclasses'
|
||||
run(cmd)
|
||||
install_slang_compiler()
|
||||
install_fonts()
|
||||
|
||||
|
||||
def set_slangc() -> None:
|
||||
slangc = os.path.join(SW if is_bundle else SLANG_INSTALL_DIR, 'bin', 'slangc')
|
||||
os.environ['SLANGC'] = slangc
|
||||
|
||||
|
||||
def build_kitty() -> None:
|
||||
python = shutil.which('python3') if is_bundle else sys.executable
|
||||
cmd = f'{python} setup.py build --verbose'
|
||||
if running_under_sanitizer:
|
||||
cmd += ' --debug --sanitize'
|
||||
set_slangc()
|
||||
run(cmd)
|
||||
|
||||
|
||||
def test_kitty() -> None:
|
||||
if is_macos:
|
||||
run('ulimit -c unlimited')
|
||||
run('sudo chmod -R 777 /cores')
|
||||
if running_under_sanitizer:
|
||||
os.environ['MallocNanoZone'] = '0'
|
||||
set_slangc()
|
||||
run('./test.py', print_crash_reports=True)
|
||||
|
||||
|
||||
def package_kitty() -> None:
|
||||
set_slangc()
|
||||
python = 'python3' if is_macos else 'python'
|
||||
run(f'{python} setup.py linux-package --update-check-interval=0 --verbose')
|
||||
run('make FAIL_WARN=1 docs')
|
||||
if is_macos:
|
||||
run('python3 setup.py kitty.app --update-check-interval=0 --verbose')
|
||||
run('kitty.app/Contents/MacOS/kitty +runpy "from kitty.constants import *; print(kitty_exe())"')
|
||||
|
||||
|
||||
def replace_in_file(path: str, src: str, dest: str) -> None:
|
||||
with open(path, 'r+') as f:
|
||||
n = f.read().replace(src, dest)
|
||||
f.seek(0), f.truncate()
|
||||
f.write(n)
|
||||
|
||||
|
||||
def setup_bundle_env() -> None:
|
||||
global SW
|
||||
os.environ['SW'] = SW = '/Users/Shared/kitty-build/sw/sw' if is_macos else os.path.join(os.environ['GITHUB_WORKSPACE'], 'sw')
|
||||
os.environ['PKG_CONFIG_PATH'] = os.path.join(SW, 'lib', 'pkgconfig')
|
||||
if is_macos:
|
||||
os.environ['PATH'] = '{}:{}'.format('/usr/local/opt/sphinx-doc/bin', os.environ['PATH'])
|
||||
else:
|
||||
os.environ['LD_LIBRARY_PATH'] = os.path.join(SW, 'lib')
|
||||
os.environ['PYTHONHOME'] = SW
|
||||
os.environ['PATH'] = '{}:{}'.format(os.path.join(SW, 'bin'), os.environ['PATH'])
|
||||
|
||||
|
||||
def install_bundle(dest: str = '', which: str = '') -> None:
|
||||
dest = dest or SW
|
||||
cwd = os.getcwd()
|
||||
os.makedirs(dest, exist_ok=True)
|
||||
os.chdir(dest)
|
||||
which = which or ('macos' if is_macos else 'linux')
|
||||
data = download_with_retry(BUNDLE_URL.format(which))
|
||||
with tarfile.open(fileobj=io.BytesIO(data), mode='r:xz') as tf:
|
||||
try:
|
||||
tf.extractall(filter='fully_trusted')
|
||||
except TypeError:
|
||||
tf.extractall()
|
||||
if not is_macos:
|
||||
replaced = 0
|
||||
for dirpath, dirnames, filenames in os.walk('.'):
|
||||
for f in filenames:
|
||||
if f.endswith('.pc') or (f.endswith('.py') and f.startswith('_sysconfig')):
|
||||
replace_in_file(os.path.join(dirpath, f), '/sw/sw', dest)
|
||||
replaced += 1
|
||||
if replaced < 2:
|
||||
raise SystemExit('Failed to replace path to SW in bundle')
|
||||
os.chdir(cwd)
|
||||
|
||||
|
||||
def install_grype(exe: str = '/tmp/grype') -> str:
|
||||
raw = download_with_retry('https://download.calibre-ebook.com/ci/grype.xz')
|
||||
raw = lzma.decompress(raw)
|
||||
with open(exe, 'wb') as f:
|
||||
f.write(raw)
|
||||
os.fchmod(f.fileno(), 0o755)
|
||||
subprocess.check_call([exe, 'db', 'update'])
|
||||
return exe
|
||||
|
||||
|
||||
IGNORED_DEPENDENCY_CVES = [
|
||||
# Python stdlib
|
||||
'CVE-2025-8194', # DoS in tarfile
|
||||
'CVE-2025-6069', # DoS in HTMLParser
|
||||
'CVE-2025-13836', # DoS in http client reading from malicious server
|
||||
'CVE-2025-12084', # DoS in xml.dom.minidom unused in kitty
|
||||
'CVE-2025-13837', # DoS in plistlib reading plist. We only use plistlib for writing
|
||||
'CVE-2025-6075', # Quadratic complexity in os.path.expandvars()
|
||||
# python stdlib all these are erroneously marked as fixed in python 3.15
|
||||
# when it hasnt even been released. Sigh.
|
||||
'CVE-2026-1299',
|
||||
'CVE-2026-0865',
|
||||
'CVE-2025-15282',
|
||||
'CVE-2026-0672',
|
||||
'CVE-2025-15366',
|
||||
'CVE-2025-15367',
|
||||
'CVE-2025-12781',
|
||||
'CVE-2025-11468',
|
||||
'CVE-2026-2297',
|
||||
'CVE-2026-3644',
|
||||
'CVE-2026-4224',
|
||||
'CVE-2026-4519',
|
||||
'CVE-2026-1502',
|
||||
'CVE-2026-7210', # DoS in unused XML parser
|
||||
'CVE-2026-3276', # DoS in unicodedata.normalize()
|
||||
'CVE-2026-7774', # tarfile.data_filter path traversal bypass
|
||||
'CVE-2026-12003', # bug in release builds irrelevant to us
|
||||
'CVE-2026-15308', # bug in stdlib html parser irrelevant to us
|
||||
'CVE-2026-11940', # tarfile, unused
|
||||
'CVE-2026-11972', # tarfile, unused
|
||||
'CVE-2026-0864', # configparser unused
|
||||
'CVE-2026-17084', # idna encoding, unused
|
||||
'CVE-2026-15806', # HTTPPasswordMgr unused
|
||||
'CVE-2026-15310', # DoS in unzip
|
||||
'CVE-2026-87910', # tarfile extract on systems without links irrelevant
|
||||
'CVE-2026-12345', # tempfile.TemporaryDirectory cleanup symlink attack
|
||||
'CVE-2026-103995', # http response header parsing in stdlib, inapplicable
|
||||
# github.com/nwaples/rardecode/v2
|
||||
'CVE-2025-11579', # rardecode is version 2.2.1, not vulnerable
|
||||
]
|
||||
|
||||
|
||||
def check_dependencies() -> None:
|
||||
grype = install_grype()
|
||||
with open((gc := os.path.expanduser('~/.grype.yml')), 'w') as f:
|
||||
print('ignore:', file=f)
|
||||
for x in IGNORED_DEPENDENCY_CVES:
|
||||
print(' - vulnerability:', x, file=f)
|
||||
dest = os.path.join(SW, 'linux')
|
||||
os.makedirs(dest, exist_ok=True)
|
||||
install_bundle(dest, os.path.basename(dest))
|
||||
dest = os.path.join(SW, 'macos')
|
||||
os.makedirs(dest, exist_ok=True)
|
||||
install_bundle(dest, os.path.basename(dest))
|
||||
cmdline = [grype, '--by-cve', '--config', gc, '--fail-on', 'medium', '--only-fixed', '--add-cpes-if-none']
|
||||
if (subprocess.run(cmdline + ['dir:' + SW])).returncode != 0:
|
||||
raise SystemExit('grype found problems during filesystem scan')
|
||||
# Now test against the SBOM
|
||||
import runpy
|
||||
|
||||
orig = sys.argv, sys.stdout
|
||||
sys.argv = ['bypy', 'sbom', 'kovidgoyal/kitty', '1.0.0']
|
||||
buf = io.StringIO()
|
||||
sys.stdout = buf
|
||||
runpy.run_path('bypy-src')
|
||||
sys.argv, sys.stdout = orig
|
||||
print(buf.getvalue())
|
||||
if (subprocess.run(cmdline, input=buf.getvalue().encode())).returncode != 0:
|
||||
raise SystemExit('grype found problems during SBOM scan')
|
||||
|
||||
|
||||
def main() -> None:
|
||||
if is_bundle:
|
||||
setup_bundle_env()
|
||||
else:
|
||||
if not is_macos and 'pythonLocation' in os.environ:
|
||||
os.environ['LD_LIBRARY_PATH'] = os.path.join(os.environ['pythonLocation'], 'lib')
|
||||
action = sys.argv[-1]
|
||||
if action in ('build', 'package'):
|
||||
install_deps()
|
||||
if action == 'build':
|
||||
build_kitty()
|
||||
elif action == 'package':
|
||||
build_kitty()
|
||||
test_kitty()
|
||||
package_kitty()
|
||||
elif action == 'test':
|
||||
test_kitty()
|
||||
elif action == 'govulncheck':
|
||||
subprocess.check_call(['go', 'install', 'golang.org/x/vuln/cmd/govulncheck@latest'])
|
||||
subprocess.check_call(['govulncheck', '-mode=binary', 'kitty/launcher/kitten'])
|
||||
subprocess.check_call(['govulncheck', './...'])
|
||||
elif action == 'check_code_formatting':
|
||||
q = subprocess.check_output('gofmt -s -l tools kittens'.split()).decode()
|
||||
if q.strip():
|
||||
q = '\n'.join(filter(lambda x: not x.rstrip().endswith(('_generated.go', '_generated_test.go')), q.strip().splitlines())).strip()
|
||||
if q:
|
||||
raise SystemExit(q)
|
||||
if subprocess.run(['ruff', 'format', '--check']).returncode != 0:
|
||||
raise SystemExit('Some Python files are not formatted correctly')
|
||||
c_files = subprocess.check_output(['git', 'ls-files', '*.c', '*.h', '*.m']).decode().split()
|
||||
if c_files and subprocess.run(['clang-format', '--dry-run', '--Werror'] + c_files).returncode != 0:
|
||||
raise SystemExit('Some C/ObjC files are not formatted correctly')
|
||||
slang_files = subprocess.check_output(['git', 'ls-files', '*.slang']).decode().split()
|
||||
badly_formatted_slang = []
|
||||
for sf in slang_files:
|
||||
assume_name = os.path.basename(sf) + '.cs'
|
||||
with open(sf, 'rb') as f:
|
||||
result = subprocess.run(['clang-format', '--style=file:.clang-format-for-slang', '--Werror', '-n', f'--assume-filename={assume_name}'], stdin=f)
|
||||
if result.returncode != 0:
|
||||
badly_formatted_slang.append(sf)
|
||||
if badly_formatted_slang:
|
||||
raise SystemExit('Some .slang files are not formatted correctly:\n' + '\n'.join(badly_formatted_slang))
|
||||
elif action == 'check-dependencies':
|
||||
check_dependencies()
|
||||
else:
|
||||
raise SystemExit(f'Unknown action: {action}')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -1,207 +0,0 @@
|
||||
name: CI
|
||||
on: [pull_request]
|
||||
env:
|
||||
CI: 'true'
|
||||
ASAN_OPTIONS: detect_leaks=0
|
||||
LC_ALL: en_US.UTF-8
|
||||
LANG: en_US.UTF-8
|
||||
|
||||
permissions:
|
||||
contents: read # to fetch code (actions/checkout)
|
||||
|
||||
jobs:
|
||||
linux:
|
||||
name: Linux (python=${{ matrix.pyver }} cc=${{ matrix.cc }} sanitize=${{ matrix.sanitize }})
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
CC: ${{ matrix.cc }}
|
||||
KITTY_SANITIZE: ${{ matrix.sanitize }}
|
||||
|
||||
strategy:
|
||||
matrix:
|
||||
python: [a, b, c]
|
||||
cc: [gcc, clang]
|
||||
include:
|
||||
- python: a
|
||||
pyver: "3.12"
|
||||
sanitize: 0
|
||||
|
||||
- python: b
|
||||
pyver: "3.13"
|
||||
sanitize: 1
|
||||
|
||||
- python: c
|
||||
pyver: "3.14"
|
||||
sanitize: 1
|
||||
|
||||
|
||||
exclude:
|
||||
- python: a
|
||||
cc: clang
|
||||
- python: b
|
||||
cc: clang
|
||||
- python: c
|
||||
cc: gcc
|
||||
|
||||
steps:
|
||||
- name: Checkout source code
|
||||
uses: actions/checkout@v7.0.1
|
||||
with:
|
||||
fetch-depth: 10
|
||||
persist-credentials: false
|
||||
|
||||
- name: Set up Python ${{ matrix.pyver }}
|
||||
uses: actions/setup-python@v7.1.0
|
||||
with:
|
||||
python-version: ${{ matrix.pyver }}
|
||||
|
||||
- name: Install Go
|
||||
uses: actions/setup-go@v7.0.0
|
||||
with:
|
||||
go-version-file: go.mod
|
||||
|
||||
- name: Build kitty
|
||||
run: python .github/workflows/ci.py build
|
||||
|
||||
- name: Test kitty
|
||||
run: python .github/workflows/ci.py test
|
||||
|
||||
linux-package:
|
||||
name: Linux package
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
CFLAGS: -funsigned-char
|
||||
steps:
|
||||
- name: Checkout source code
|
||||
uses: actions/checkout@v7.0.1
|
||||
with:
|
||||
fetch-depth: 0 # needed for :commit: docs role
|
||||
persist-credentials: false
|
||||
|
||||
- name: Test for trailing whitespace
|
||||
run: if grep -Inr '\s$' kitty kitty_tests kittens docs *.py *.asciidoc *.rst *.go .gitattributes .gitignore; then echo Trailing whitespace found, aborting.; exit 1; fi
|
||||
|
||||
- name: Test for bad code block formatting
|
||||
run: if grep -Inr ':code:`\s' kitty kitty_tests kittens docs *.py *.asciidoc *.rst *.go .gitattributes .gitignore; then echo Space at code block start found, aborting.; exit 1; fi
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v7.1.0
|
||||
with:
|
||||
python-version: "3.14"
|
||||
|
||||
- name: Install Go
|
||||
uses: actions/setup-go@v7.0.0
|
||||
with:
|
||||
go-version-file: go.mod
|
||||
cache: false
|
||||
|
||||
- name: Cache Go build artifacts for static kittens
|
||||
uses: actions/cache@v6.1.0
|
||||
with:
|
||||
path: |
|
||||
~/.cache/go-build
|
||||
~/go/pkg/mod
|
||||
key: ${{ runner.os }}-golang-static-${{ hashFiles('**/go.sum') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-golang-static-
|
||||
|
||||
- name: Install build-only deps
|
||||
run: python -m pip install -r docs/requirements.txt ruff ty types-requests types-docutils types-Pygments clang-format
|
||||
|
||||
- name: Run ruff
|
||||
run: ruff check .
|
||||
|
||||
- name: Check code formatting
|
||||
run: go version && python .github/workflows/ci.py check_code_formatting
|
||||
|
||||
- name: Build kitty package
|
||||
run: python .github/workflows/ci.py package
|
||||
|
||||
- name: Run type checking
|
||||
run: which python && ./test.py type-check
|
||||
|
||||
- name: Run go vet
|
||||
run: go version && go vet -tags testing ./...
|
||||
|
||||
- name: Build static kittens
|
||||
run: python setup.py build-static-binaries
|
||||
|
||||
bundle:
|
||||
name: Bundle test (${{ matrix.os }})
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
matrix:
|
||||
os: [ubuntu-latest, macos-latest]
|
||||
env:
|
||||
KITTY_BUNDLE: 1
|
||||
KITTY_SANITIZE: 1
|
||||
steps:
|
||||
- name: Checkout source code
|
||||
uses: actions/checkout@v7.0.1
|
||||
with:
|
||||
fetch-depth: 10
|
||||
persist-credentials: false
|
||||
|
||||
- name: Install Go
|
||||
uses: actions/setup-go@v7.0.0
|
||||
with:
|
||||
go-version-file: go.mod
|
||||
|
||||
- name: Build kitty
|
||||
run: which python3 && python3 .github/workflows/ci.py build
|
||||
|
||||
- name: Test kitty
|
||||
run: python3 .github/workflows/ci.py test
|
||||
|
||||
brew:
|
||||
name: macOS Brew
|
||||
runs-on: macos-latest
|
||||
steps:
|
||||
- name: Checkout source code
|
||||
uses: actions/checkout@v7.0.1
|
||||
with:
|
||||
fetch-depth: 0 # needed for :commit: docs role
|
||||
persist-credentials: false
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v7.1.0
|
||||
with:
|
||||
python-version: "3.14"
|
||||
|
||||
- name: Install Go
|
||||
uses: actions/setup-go@v7.0.0
|
||||
with:
|
||||
go-version-file: go.mod
|
||||
|
||||
- name: Install deps for docs
|
||||
run: python3 -m pip install -r docs/requirements.txt
|
||||
|
||||
- name: Build kitty package
|
||||
run: python3 .github/workflows/ci.py package
|
||||
|
||||
- name: Run benchmarks
|
||||
run: ./benchmark.py
|
||||
|
||||
linux-dev:
|
||||
name: Test ./dev.sh and benchmark
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout source code
|
||||
uses: actions/checkout@v7.0.1
|
||||
with:
|
||||
fetch-depth: 10
|
||||
persist-credentials: false
|
||||
|
||||
- name: Install build deps
|
||||
run: sudo apt-get update && sudo apt-get install -y curl xz-utils build-essential git pkg-config libxrandr-dev libxinerama-dev libxcursor-dev libxi-dev libgl1-mesa-dev libxkbcommon-x11-dev libfontconfig-dev libx11-xcb-dev libdbus-1-dev
|
||||
|
||||
- name: Install Go
|
||||
uses: actions/setup-go@v7.0.0
|
||||
with:
|
||||
go-version-file: go.mod
|
||||
|
||||
- name: Build kitty
|
||||
run: ./dev.sh build
|
||||
|
||||
- name: Run benchmarks
|
||||
run: ./benchmark.py
|
||||
@@ -1,69 +0,0 @@
|
||||
name: "CodeQL"
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
# The branches below must be a subset of the branches above
|
||||
branches: [master]
|
||||
schedule:
|
||||
- cron: '0 22 * * 5'
|
||||
|
||||
jobs:
|
||||
CodeQL-Build:
|
||||
|
||||
permissions:
|
||||
contents: read # to fetch code (actions/checkout)
|
||||
security-events: write # to upload SARIF results (github/codeql-action/analyze)
|
||||
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- language: python
|
||||
os: ubuntu-latest
|
||||
- language: c
|
||||
os: ubuntu-latest
|
||||
- language: c
|
||||
os: macos-latest
|
||||
- language: go
|
||||
os: ubuntu-latest
|
||||
- language: actions
|
||||
os: ubuntu-latest
|
||||
|
||||
runs-on: ${{ matrix.os }}
|
||||
env:
|
||||
KITTY_BUNDLE: 1
|
||||
KITTY_CODEQL: 1
|
||||
|
||||
steps:
|
||||
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v7.0.1
|
||||
with:
|
||||
# We must fetch at least the immediate parents so that if this is
|
||||
# a pull request then we can checkout the head.
|
||||
fetch-depth: 2
|
||||
persist-credentials: false
|
||||
|
||||
- name: Install Go
|
||||
if: matrix.language == 'c' || matrix.language == 'go'
|
||||
uses: actions/setup-go@v7.0.0
|
||||
with:
|
||||
go-version-file: go.mod
|
||||
|
||||
# Initializes the CodeQL tools for scanning.
|
||||
- name: Initialize CodeQL
|
||||
uses: github/codeql-action/init@v4.39.1
|
||||
with:
|
||||
languages: ${{ matrix.language }}
|
||||
trap-caching: false
|
||||
|
||||
- name: Build kitty
|
||||
if: matrix.language == 'c' || matrix.language == 'go'
|
||||
run: python3 .github/workflows/ci.py build
|
||||
|
||||
- name: Perform CodeQL Analysis
|
||||
uses: github/codeql-action/analyze@v4.39.1
|
||||
|
||||
- name: Run govulncheck
|
||||
if: matrix.language == 'go'
|
||||
run: python3 .github/workflows/ci.py govulncheck
|
||||
@@ -1,37 +0,0 @@
|
||||
name: Depscan
|
||||
on:
|
||||
schedule:
|
||||
- cron: '0 12 * * 5'
|
||||
|
||||
env:
|
||||
CI: 'true'
|
||||
ASAN_OPTIONS: detect_leaks=0
|
||||
LC_ALL: en_US.UTF-8
|
||||
LANG: en_US.UTF-8
|
||||
|
||||
permissions:
|
||||
contents: read # to fetch code (actions/checkout)
|
||||
|
||||
jobs:
|
||||
dependecy-scanner:
|
||||
name: Scan dependencies for vulnerabilities
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
KITTY_BUNDLE: 1
|
||||
steps:
|
||||
- name: Checkout source code
|
||||
uses: actions/checkout@v7.0.1
|
||||
with:
|
||||
fetch-depth: 10
|
||||
persist-credentials: false
|
||||
|
||||
- name: Checkout bypy
|
||||
uses: actions/checkout@v7.0.1
|
||||
with:
|
||||
fetch-depth: 1
|
||||
persist-credentials: false
|
||||
repository: kovidgoyal/bypy
|
||||
path: bypy-src
|
||||
|
||||
- name: Check dependencies
|
||||
run: python3 .github/workflows/ci.py check-dependencies
|
||||
@@ -1,541 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2024, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
import json
|
||||
import os
|
||||
import posixpath
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
from collections import defaultdict, namedtuple
|
||||
from datetime import datetime
|
||||
from enum import Enum
|
||||
from functools import cached_property
|
||||
from typing import IO, Mapping, Optional
|
||||
|
||||
Frame = namedtuple('Frame', 'image_name image_base image_offset symbol symbol_offset')
|
||||
Register = namedtuple('Register', 'name value')
|
||||
|
||||
# Cache mapping filename (basename) -> absolute path, built once on first use.
|
||||
_build_file_cache: Optional[dict[str, str]] = None
|
||||
|
||||
|
||||
def _build_filename_cache() -> dict[str, str]:
|
||||
"""Walk the repo build tree and map each filename to its absolute path.
|
||||
|
||||
The script lives at <repo>/.github/workflows/, so the repo root is two
|
||||
levels up. We scan the whole repo tree so we find both in-tree build
|
||||
artefacts (e.g. kitty/fast_data_types.so) and those under build/.
|
||||
"""
|
||||
cache: dict[str, str] = {}
|
||||
repo_root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
for dirpath, _dirnames, filenames in os.walk(repo_root):
|
||||
for fname in filenames:
|
||||
# Keep the first occurrence (shallowest path wins).
|
||||
if fname not in cache:
|
||||
cache[fname] = os.path.join(dirpath, fname)
|
||||
return cache
|
||||
|
||||
|
||||
def _resolve_image_path(image_path: str) -> str:
|
||||
"""Return the real filesystem path for *image_path*.
|
||||
|
||||
Crash reports on macOS redact parts of paths for privacy, replacing
|
||||
directory components with ``*`` (e.g. ``/Users/USER/*/fast_data_types.so``).
|
||||
These are *not* glob patterns — the ``*`` is a literal privacy placeholder.
|
||||
When such a path is detected, look up the basename in the build-file cache.
|
||||
"""
|
||||
if '*' not in image_path and '?' not in image_path:
|
||||
return image_path
|
||||
|
||||
global _build_file_cache
|
||||
if _build_file_cache is None:
|
||||
_build_file_cache = _build_filename_cache()
|
||||
|
||||
basename = os.path.basename(image_path)
|
||||
return _build_file_cache.get(basename, image_path)
|
||||
|
||||
|
||||
def _get_source_locations(frames: list[Frame]) -> dict[int, str]:
|
||||
"""Use atos to look up source file and line number for each frame.
|
||||
|
||||
Returns a mapping of frame index -> 'source_file:line_number' string.
|
||||
Only frames with a known image path and base address are processed.
|
||||
"""
|
||||
# Group frames by (image_path, load_address) so we can batch atos calls.
|
||||
by_image: dict[tuple[str, int], list[tuple[int, int]]] = defaultdict(list) # (path, base) -> [(address, frame_idx)]
|
||||
for i, frame in enumerate(frames):
|
||||
if frame.image_name and frame.image_base is not None and frame.image_offset is not None:
|
||||
addr = frame.image_base + frame.image_offset
|
||||
by_image[(frame.image_name, frame.image_base)].append((addr, i))
|
||||
|
||||
result: dict[int, str] = {}
|
||||
for (image_path, load_addr), addr_frame_pairs in by_image.items():
|
||||
addresses = [addr for addr, _ in addr_frame_pairs]
|
||||
frame_indices = [idx for _, idx in addr_frame_pairs]
|
||||
# Paths in crash reports may have privacy-redacted components (e.g.
|
||||
# /Users/USER/*/fast_data_types.so). Resolve to a real path using the
|
||||
# cached build-file index before passing to atos.
|
||||
resolved_path = _resolve_image_path(image_path)
|
||||
try:
|
||||
cmd = ['atos', '-o', resolved_path, '-l', hex(load_addr)] + [hex(a) for a in addresses]
|
||||
proc = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
|
||||
if proc.returncode == 0:
|
||||
lines = proc.stdout.splitlines()
|
||||
for frame_idx, line in zip(frame_indices, lines):
|
||||
# atos output: "func_name (in binary) (source_file:line)"
|
||||
# Extract the trailing "(file:line)" part. Use [^:]+ for the
|
||||
# file portion since colons in filenames are rare/invalid on
|
||||
# macOS, and this avoids false-matches with parentheses in paths.
|
||||
m = re.search(r'\(([^:()]+:\d+)\)\s*$', line)
|
||||
if m:
|
||||
result[frame_idx] = m.group(1)
|
||||
except (OSError, subprocess.SubprocessError):
|
||||
pass
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def surround(x: str, start: int, end: int) -> str:
|
||||
if sys.stdout.isatty():
|
||||
x = f'\033[{start}m{x}\033[{end}m'
|
||||
return x
|
||||
|
||||
|
||||
def cyan(x: str) -> str:
|
||||
return surround(x, 96, 39)
|
||||
|
||||
|
||||
def bold(x: str) -> str:
|
||||
return surround(x, 1, 22)
|
||||
|
||||
|
||||
class BugType(Enum):
|
||||
WatchdogTimeout = '28'
|
||||
BasebandStats = '195'
|
||||
GPUEvent = '284'
|
||||
Sandbox = '187'
|
||||
TerminatingStackshot = '509'
|
||||
ServiceWatchdogTimeout = '29'
|
||||
Session = '179'
|
||||
LegacyStackshot = '188'
|
||||
MACorrelation = '197'
|
||||
iMessages = '189'
|
||||
log_power = '278'
|
||||
PowerLog = 'powerlog'
|
||||
DuetKnowledgeCollector2 = '58'
|
||||
BridgeRestore = '83'
|
||||
LegacyJetsam = '198'
|
||||
ExcResource_385 = '385'
|
||||
Modem = '199'
|
||||
Stackshot = '288'
|
||||
SystemInformation = 'system_profile'
|
||||
Jetsam_298 = '298'
|
||||
MemoryResource = '30'
|
||||
Bridge = '31'
|
||||
DifferentialPrivacy = 'diff_privacy'
|
||||
FirmwareIntegrity = '32'
|
||||
CoreAnalytics_33 = '33'
|
||||
AutoBugCapture = '34'
|
||||
EfiFirmwareIntegrity = '35'
|
||||
SystemStats = '36'
|
||||
AnonSystemStats = '37'
|
||||
Crash_9 = '9'
|
||||
Jetsam_98 = '98'
|
||||
LDCM = '100'
|
||||
Panic_10 = '10'
|
||||
Spin = '11'
|
||||
CLTM = '101'
|
||||
Hang = '12'
|
||||
Panic_110 = '110'
|
||||
ConnectionFailure = '13'
|
||||
MessageTracer = '14'
|
||||
LowBattery = '120'
|
||||
Siri = '201'
|
||||
ShutdownStall = '17'
|
||||
Panic_210 = '210'
|
||||
SymptomsCPUUsage = '202'
|
||||
AssumptionViolation = '18'
|
||||
CoreHandwriting = 'chw'
|
||||
IOMicroStackShot = '44'
|
||||
CoreAnalytics_211 = '211'
|
||||
SiriAppPrediction = '203'
|
||||
spin_45 = '45'
|
||||
PowerMicroStackshots = '220'
|
||||
BTMetadata = '212'
|
||||
SystemMemoryReset = '301'
|
||||
ResetCount = '115'
|
||||
AutoBugCapture_204 = '204'
|
||||
WifiCrashBinary = '221'
|
||||
MicroRunloopHang = '310'
|
||||
Rosetta = '213'
|
||||
glitchyspin = '302'
|
||||
System = '116'
|
||||
IOPowerSources = '141'
|
||||
PanicStats = '205'
|
||||
PowerLog_230 = '230'
|
||||
LongRunloopHang = '222'
|
||||
HomeProductsAnalytics = '311'
|
||||
DifferentialPrivacy_150 = '150'
|
||||
Rhodes = '214'
|
||||
ProactiveEventTrackerTransparency = '303'
|
||||
WiFi = '117'
|
||||
SymptomsCPUWakes = '142'
|
||||
SymptomsCPUUsageFatal = '206'
|
||||
Crash_109 = '109'
|
||||
ShortRunloopHang = '223'
|
||||
CoreHandwriting_231 = '231'
|
||||
ForceReset = '151'
|
||||
SiriAppSelection = '215'
|
||||
PrivateFederatedLearning = '304'
|
||||
Bluetooth = '118'
|
||||
SCPMotion = '143'
|
||||
HangSpin = '207'
|
||||
StepCount = '160'
|
||||
RTCTransparency = '224'
|
||||
DiagnosticRequest = '312'
|
||||
MemorySnapshot = '152'
|
||||
Rosetta_B = '216'
|
||||
AudioAccessory = '305'
|
||||
General = '119'
|
||||
HotSpotIOMicroSS = '144'
|
||||
GeoServicesTransparency = '233'
|
||||
MotionState = '161'
|
||||
AppStoreTransparency = '225'
|
||||
SiriSearchFeedback = '313'
|
||||
BearTrapReserved = '153'
|
||||
Portrait = '217'
|
||||
AWDMetricLog = 'metriclog'
|
||||
SymptomsIO = '145'
|
||||
SubmissionReserved = '170'
|
||||
WifiCrash = '209'
|
||||
Natalies = '162'
|
||||
SecurityTransparency = '226'
|
||||
BiomeMapReduce = '234'
|
||||
MemoryGraph = '154'
|
||||
MultichannelAudio = '218'
|
||||
honeybee_payload = '146'
|
||||
MesaReserved = '171'
|
||||
WifiSensing = '235'
|
||||
SiriMiss = '163'
|
||||
ExcResourceThreads_227 = '227'
|
||||
TestA = 'T01'
|
||||
NetworkUsage = '155'
|
||||
WifiReserved = '180'
|
||||
SiriActionPrediction = '219'
|
||||
honeybee_heartbeat = '147'
|
||||
ECCEvent = '172'
|
||||
KeyTransparency = '236'
|
||||
SubDiagHeartBeat = '164'
|
||||
ThirdPartyHang = '228'
|
||||
OSFault = '308'
|
||||
CoreTime = '156'
|
||||
WifiDriverReserved = '181'
|
||||
Crash_309 = '309'
|
||||
honeybee_issue = '148'
|
||||
CellularPerfReserved = '173'
|
||||
TestB = 'T02'
|
||||
StorageStatus = '165'
|
||||
SiriNotificationTransparency = '229'
|
||||
TestC = 'T03'
|
||||
CPUMicroSS = '157'
|
||||
AccessoryUpdate = '182'
|
||||
xprotect = '20'
|
||||
MultitouchFirmware = '149'
|
||||
MicroStackshot = '174'
|
||||
AppLaunchDiagnostics = '238'
|
||||
KeyboardAccuracy = '166'
|
||||
GPURestart = '21'
|
||||
FaceTime = '191'
|
||||
DuetKnowledgeCollector = '158'
|
||||
OTASUpdate = '183'
|
||||
ExcResourceThreads_327 = '327'
|
||||
ExcResource_22 = '22'
|
||||
DuetDB = '175'
|
||||
ThirdPartyHangDeveloper = '328'
|
||||
PrivacySettings = '167'
|
||||
GasGauge = '192'
|
||||
MicroStackShots = '23'
|
||||
BasebandCrash = '159'
|
||||
GPURestart_184 = '184'
|
||||
SystemWatchdogCrash = '409'
|
||||
FlashStatus = '176'
|
||||
SleepWakeFailure = '24'
|
||||
CarouselEvent = '168'
|
||||
AggregateD = '193'
|
||||
WakeupsMonitorViolation = '25'
|
||||
DifferentialPrivacy_50 = '50'
|
||||
ExcResource_185 = '185'
|
||||
UIAutomation = '177'
|
||||
ping = '26'
|
||||
SiriTransaction = '169'
|
||||
SURestore = '194'
|
||||
KtraceStackshot = '186'
|
||||
WirelessDiagnostics = '27'
|
||||
PowerLogLite = '178'
|
||||
SKAdNetworkAnalytics = '237'
|
||||
HangWorkflowResponsiveness = '239'
|
||||
CompositorClientHang = '243'
|
||||
|
||||
|
||||
class CrashReportBase:
|
||||
def __init__(self, metadata: Mapping, data: str, filename: str = None):
|
||||
self.filename = filename
|
||||
self._metadata = metadata
|
||||
self._data = data
|
||||
self._parse()
|
||||
|
||||
def _parse(self) -> None:
|
||||
self._is_json = False
|
||||
try:
|
||||
modified_data = self._data
|
||||
if '\n \n' in modified_data:
|
||||
modified_data, rest = modified_data.split('\n \n', 1)
|
||||
rest = '",' + rest.split('",', 1)[1]
|
||||
modified_data += rest
|
||||
self._data = json.loads(modified_data)
|
||||
self._is_json = True
|
||||
except json.decoder.JSONDecodeError:
|
||||
pass
|
||||
|
||||
@cached_property
|
||||
def bug_type(self) -> BugType:
|
||||
return BugType(self.bug_type_str)
|
||||
|
||||
@cached_property
|
||||
def bug_type_str(self) -> str:
|
||||
return self._metadata['bug_type']
|
||||
|
||||
@cached_property
|
||||
def incident_id(self) -> str:
|
||||
return self._metadata.get('incident_id')
|
||||
|
||||
@cached_property
|
||||
def timestamp(self) -> datetime:
|
||||
timestamp = self._metadata.get('timestamp')
|
||||
timestamp_without_timezone = timestamp.rsplit(' ', 1)[0]
|
||||
return datetime.strptime(timestamp_without_timezone, '%Y-%m-%d %H:%M:%S.%f')
|
||||
|
||||
@cached_property
|
||||
def name(self) -> str:
|
||||
return self._metadata.get('name')
|
||||
|
||||
def __repr__(self) -> str:
|
||||
filename = ''
|
||||
if self.filename:
|
||||
filename = f'FILENAME:{posixpath.basename(self.filename)} '
|
||||
return f'<{self.__class__} {filename}TIMESTAMP:{self.timestamp}>'
|
||||
|
||||
def __str__(self) -> str:
|
||||
filename = ''
|
||||
if self.filename:
|
||||
filename = self.filename
|
||||
|
||||
return cyan(f'{self.incident_id} {self.timestamp}\n{filename}\n\n')
|
||||
|
||||
|
||||
class UserModeCrashReport(CrashReportBase):
|
||||
def _parse_field(self, name: str) -> str:
|
||||
name += ':'
|
||||
for line in self._data.split('\n'):
|
||||
if line.startswith(name):
|
||||
field = line.split(name, 1)[1]
|
||||
field = field.strip()
|
||||
return field
|
||||
|
||||
@cached_property
|
||||
def faulting_thread(self) -> int:
|
||||
if self._is_json:
|
||||
return self._data['faultingThread']
|
||||
else:
|
||||
return int(self._parse_field('Triggered by Thread'))
|
||||
|
||||
@cached_property
|
||||
def frames(self) -> list[Frame]:
|
||||
result = []
|
||||
if self._is_json:
|
||||
thread_index = self.faulting_thread
|
||||
images = self._data['usedImages']
|
||||
for frame in self._data['threads'][thread_index]['frames']:
|
||||
image = images[frame['imageIndex']]
|
||||
result.append(
|
||||
Frame(
|
||||
image_name=image.get('path'),
|
||||
image_base=image.get('base'),
|
||||
symbol=frame.get('symbol'),
|
||||
image_offset=frame.get('imageOffset'),
|
||||
symbol_offset=frame.get('symbolLocation'),
|
||||
)
|
||||
)
|
||||
else:
|
||||
in_frames = False
|
||||
for line in self._data.split('\n'):
|
||||
if in_frames:
|
||||
splitted = line.split()
|
||||
|
||||
if len(splitted) == 0:
|
||||
break
|
||||
|
||||
assert splitted[-2] == '+'
|
||||
image_base = splitted[-3]
|
||||
if image_base.startswith('0x'):
|
||||
result.append(
|
||||
Frame(image_name=splitted[1], image_base=int(image_base, 16), symbol=None, image_offset=int(splitted[-1]), symbol_offset=None)
|
||||
)
|
||||
else:
|
||||
# symbolicated
|
||||
result.append(Frame(image_name=splitted[1], image_base=None, symbol=image_base, image_offset=None, symbol_offset=int(splitted[-1])))
|
||||
|
||||
if line.startswith(f'Thread {self.faulting_thread} Crashed:'):
|
||||
in_frames = True
|
||||
|
||||
return result
|
||||
|
||||
@cached_property
|
||||
def registers(self) -> list[Register]:
|
||||
result = []
|
||||
if self._is_json:
|
||||
thread_index = self._data['faultingThread']
|
||||
thread_state = self._data['threads'][thread_index]['threadState']
|
||||
|
||||
if 'x' in thread_state:
|
||||
for i, reg_x in enumerate(thread_state['x']):
|
||||
result.append(Register(name=f'x{i}', value=reg_x['value']))
|
||||
|
||||
for i, (name, value) in enumerate(thread_state.items()):
|
||||
if name == 'x':
|
||||
for j, reg_x in enumerate(value):
|
||||
result.append(Register(name=f'x{j}', value=reg_x['value']))
|
||||
else:
|
||||
if isinstance(value, dict):
|
||||
result.append(Register(name=name, value=value['value']))
|
||||
else:
|
||||
in_frames = False
|
||||
for line in self._data.split('\n'):
|
||||
if in_frames:
|
||||
splitted = line.split()
|
||||
|
||||
if len(splitted) == 0:
|
||||
break
|
||||
|
||||
for i in range(0, len(splitted), 2):
|
||||
register_name = splitted[i]
|
||||
if not register_name.endswith(':'):
|
||||
break
|
||||
|
||||
register_name = register_name[:-1]
|
||||
register_value = int(splitted[i + 1], 16)
|
||||
|
||||
result.append(Register(name=register_name, value=register_value))
|
||||
|
||||
if line.startswith(f'Thread {self.faulting_thread} crashed with ARM Thread State'):
|
||||
in_frames = True
|
||||
|
||||
return result
|
||||
|
||||
@cached_property
|
||||
def exception_type(self) -> str:
|
||||
if self._is_json:
|
||||
return self._data['exception'].get('type')
|
||||
else:
|
||||
return self._parse_field('Exception Type')
|
||||
|
||||
@cached_property
|
||||
def exception_subtype(self) -> Optional[str]:
|
||||
if self._is_json:
|
||||
return self._data['exception'].get('subtype')
|
||||
else:
|
||||
return self._parse_field('Exception Subtype')
|
||||
|
||||
@cached_property
|
||||
def application_specific_information(self) -> Optional[str]:
|
||||
result = ''
|
||||
if self._is_json:
|
||||
asi = self._data.get('asi')
|
||||
if asi is None:
|
||||
return None
|
||||
return asi
|
||||
else:
|
||||
in_frames = False
|
||||
for line in self._data.split('\n'):
|
||||
if in_frames:
|
||||
line = line.strip()
|
||||
if len(line) == 0:
|
||||
break
|
||||
|
||||
result += line + '\n'
|
||||
|
||||
if line.startswith('Application Specific Information:'):
|
||||
in_frames = True
|
||||
|
||||
result = result.strip()
|
||||
if not result:
|
||||
return None
|
||||
return result
|
||||
|
||||
def __str__(self) -> str:
|
||||
result = super().__str__()
|
||||
result += bold(f'Exception: {self.exception_type}\n')
|
||||
|
||||
if self.exception_subtype:
|
||||
result += bold('Exception Subtype: ')
|
||||
result += f'{self.exception_subtype}\n'
|
||||
|
||||
if self.application_specific_information:
|
||||
result += bold('Application Specific Information: ')
|
||||
result += str(self.application_specific_information)
|
||||
|
||||
result += '\n'
|
||||
|
||||
result += bold('Registers:')
|
||||
for i, register in enumerate(self.registers):
|
||||
if i % 4 == 0:
|
||||
result += '\n'
|
||||
|
||||
result += f'{register.name} = 0x{register.value:016x} '.rjust(30)
|
||||
|
||||
result += '\n\n'
|
||||
|
||||
source_locations = _get_source_locations(self.frames)
|
||||
result += bold('Frames:\n')
|
||||
for i, frame in enumerate(self.frames):
|
||||
image_base = '_HEADER'
|
||||
if frame.image_base is not None:
|
||||
image_base = f'0x{frame.image_base:x}'
|
||||
result += f'\t[{frame.image_name}] {image_base}'
|
||||
if frame.image_offset:
|
||||
result += f' + 0x{frame.image_offset:x}'
|
||||
if frame.symbol is not None:
|
||||
result += f' ({frame.symbol} + 0x{frame.symbol_offset:x})'
|
||||
if i in source_locations:
|
||||
result += f' [{source_locations[i]}]'
|
||||
result += '\n'
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def get_crash_report_from_file(crash_report_file: IO[str]) -> CrashReportBase:
|
||||
metadata = json.loads(crash_report_file.readline())
|
||||
|
||||
try:
|
||||
bug_type = BugType(metadata['bug_type'])
|
||||
except ValueError:
|
||||
return CrashReportBase(metadata, crash_report_file.read(), crash_report_file.name)
|
||||
|
||||
bug_type_parsers = {
|
||||
BugType.Crash_109: UserModeCrashReport,
|
||||
BugType.Crash_309: UserModeCrashReport,
|
||||
BugType.ExcResourceThreads_327: UserModeCrashReport,
|
||||
BugType.ExcResource_385: UserModeCrashReport,
|
||||
}
|
||||
|
||||
parser = bug_type_parsers.get(bug_type)
|
||||
if parser is None:
|
||||
return CrashReportBase(metadata, crash_report_file.read(), crash_report_file.name)
|
||||
|
||||
return parser(metadata, crash_report_file.read(), crash_report_file.name)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
with open(sys.argv[-1]) as f:
|
||||
print(get_crash_report_from_file(f))
|
||||
@@ -10,8 +10,13 @@
|
||||
*_generated.h
|
||||
*.local.md
|
||||
/dependencies
|
||||
/.venv
|
||||
/tags
|
||||
/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/
|
||||
/shaders/
|
||||
/linux-package/
|
||||
@@ -31,6 +36,7 @@ __pycache__/
|
||||
bypy/b
|
||||
bypy/virtual-machines.conf
|
||||
_codeql_detected_source_root
|
||||
/.tools/
|
||||
|
||||
# --- Local tool state and caches (never committed) ---
|
||||
.freebuff/
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
# Installer et lancer la version de développement
|
||||
|
||||
Ce document explique comment compiler puis lancer kitty depuis les sources, en
|
||||
local sur **Arch Linux** ou depuis **Windows/macOS via Docker**.
|
||||
|
||||
kitty ne se compile pas nativement sous Windows : `./dev.sh` ne fournit les
|
||||
dépendances précompilées que pour Linux et macOS. Le dépôt est donc développé
|
||||
sur Windows mais compilé et exécuté contre Arch Linux (la distribution cible),
|
||||
soit dans le conteneur fourni, soit dans un Arch natif (machine ou WSL2).
|
||||
|
||||
## Dépendances
|
||||
|
||||
Arch Linux, tous les paquets listés dans `docs/build.rst` :
|
||||
|
||||
```sh
|
||||
sudo pacman -S --needed base-devel git go python \
|
||||
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 rsync which file
|
||||
```
|
||||
|
||||
`go` doit être au moins la version indiquée dans `go.mod` (actuellement 1.26).
|
||||
|
||||
## Option 1 : Arch Linux natif
|
||||
|
||||
```sh
|
||||
git clone <url-du-depot> FWS-Kitty && cd FWS-Kitty
|
||||
./dev.sh build
|
||||
./kitty/launcher/kitty
|
||||
```
|
||||
|
||||
`./dev.sh build` télécharge les dépendances précompilées dans `dependencies/`
|
||||
(et une police NERD dans `fonts/`), puis compile le C, le Go et les kittens.
|
||||
Pour re-télécharger les dépendances : `./dev.sh deps`.
|
||||
|
||||
Raccourcis utiles :
|
||||
|
||||
```sh
|
||||
./dev.sh build --debug # symboles de debug
|
||||
./dev.sh build --debug --sanitize
|
||||
./dev.sh build -h # toutes les options
|
||||
```
|
||||
|
||||
`kitty` et `kitten` sont produits dans `kitty/launcher/`. Créez des liens
|
||||
symboliques vers eux dans un dossier de votre `PATH` pour les lancer de partout.
|
||||
L'exécutable compilé retrouve ses sources par le chemin où `./dev.sh build` a
|
||||
été lancé : si vous déplacez le dossier, faites `make clean && ./dev.sh build`.
|
||||
|
||||
### Affichage
|
||||
|
||||
kitty a besoin d'un serveur graphique. Sous Arch natif c'est votre session
|
||||
X11/Wayland. Dans WSL2, activez WSLg (Windows 11) : `./kitty/launcher/kitty`
|
||||
s'ouvre alors dans une fenêtre Windows. Sans WSLg, il faut un serveur X
|
||||
(par exemple VcXsrv) et un `DISPLAY` correct.
|
||||
|
||||
## Option 2 : Docker (depuis Windows ou macOS)
|
||||
|
||||
Le dépôt fournit `Dockerfile.arch`, une image Arch Linux avec toutes les
|
||||
dépendances ci-dessus.
|
||||
|
||||
```sh
|
||||
# construire l'image (à refaire seulement si le Dockerfile change)
|
||||
docker build -f Dockerfile.arch -t kitty-arch-dev .
|
||||
|
||||
# compiler kitty : les artefacts restent dans le dépôt
|
||||
docker run --rm -v "C:/chemin/vers/FWS-Kitty:/src" -w /src kitty-arch-dev sh dev.sh build
|
||||
|
||||
# lancer
|
||||
docker run --rm -it -v "C:/chemin/vers/FWS-Kitty:/src" -w /src kitty-arch-dev ./kitty/launcher/kitty
|
||||
```
|
||||
|
||||
Sous Git Bash, préfixez les commandes par `MSYS_NO_PATHCONV=1` pour éviter que
|
||||
les chemins `/src` soient réécrits en chemins Windows.
|
||||
|
||||
Vérification rapide sans interface graphique :
|
||||
|
||||
```sh
|
||||
docker run --rm -v "C:/chemin/vers/FWS-Kitty:/src" -w /src kitty-arch-dev \
|
||||
./kitty/launcher/kitty --version
|
||||
```
|
||||
|
||||
Le conteneur n'a pas d'affichage : pour voir la fenêtre, montez le socket X11 ou
|
||||
utilisez un Arch natif/WSLg.
|
||||
|
||||
## Tests et vérifications
|
||||
|
||||
```sh
|
||||
./test.py # suite complète (Python + Go)
|
||||
./test.py --module screen # tests d'un module Python
|
||||
./test.py MyFunction # un test Go nommé TestMyFunction
|
||||
./test.py type-check # vérification de types
|
||||
ruff check --fix # lint Python
|
||||
```
|
||||
|
||||
Le Makefile expose les mêmes entrées : `make debug`, `make test`, `make clean`.
|
||||
|
||||
## Dépannage
|
||||
|
||||
**`dev.sh: $'\r': command not found` ou `make` qui échoue** : fins de ligne
|
||||
CRLF dans l'arbre de travail. Le dépôt est normalisé en LF via `.gitattributes` ;
|
||||
corrigez localement avec :
|
||||
|
||||
```sh
|
||||
git config core.autocrlf false
|
||||
git rm --cached -r -q . && git reset --hard
|
||||
```
|
||||
|
||||
**`X11/extensions/XInput2.h: No such file or directory`** : il manque `libxi`
|
||||
(pour XInput2) sur la machine ou dans l'image.
|
||||
|
||||
**`undefined: err` dans `bypy/devenv.go`** : erreur corrigée dans le dépôt ;
|
||||
mettez à jour votre branche si vous la rencontrez.
|
||||
|
||||
**Compilation très lente sur Windows** : le montage Docker depuis `C:` est
|
||||
lent ; préférez un Arch natif/WSL pour les builds répétés.
|
||||
|
||||
**`kitty: command not found` après installation** : les binaires sont dans
|
||||
`kitty/launcher/` ; ajoutez ce dossier à votre `PATH` ou créez des liens
|
||||
symboliques.
|
||||
@@ -0,0 +1,32 @@
|
||||
# Arch Linux development environment for kitty.
|
||||
#
|
||||
# kitty only builds on Linux and macOS (./dev.sh refuses to download the
|
||||
# prebuilt dependency bundle elsewhere), so Windows hosts build and run it
|
||||
# through this container instead of natively.
|
||||
#
|
||||
# The package list mirrors docs/build.rst: the build-time requirements plus
|
||||
# the X11/Wayland/DBus libraries, installed on the distribution kitty is
|
||||
# meant to run on.
|
||||
FROM archlinux:base
|
||||
|
||||
RUN pacman -Syu --noconfirm --needed \
|
||||
base-devel \
|
||||
git go python \
|
||||
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 rsync which file \
|
||||
&& pacman -Scc --noconfirm
|
||||
|
||||
# Keep the Go caches inside the image layer so rebuilds are not slowed down by
|
||||
# the bind-mounted source directory.
|
||||
ENV GOCACHE=/root/.cache/go-build \
|
||||
GOPATH=/root/go \
|
||||
GOTOOLCHAIN=local
|
||||
|
||||
WORKDIR /src
|
||||
|
||||
CMD ["/bin/bash"]
|
||||
@@ -0,0 +1,394 @@
|
||||
# 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`.
|
||||
@@ -0,0 +1,380 @@
|
||||
# FWS-Kitty
|
||||
|
||||
FWS-Kitty est le fork **FWS** de [kitty](https://sw.kovidgoyal.net/kitty/), un
|
||||
terminal GPU rapide et riche en fonctionnalités. Le fork ajoute un
|
||||
**gestionnaire de fichiers** (`kitten file-manager`) : un panneau latéral
|
||||
pilotable au clavier qui change le répertoire courant du shell, crée, renomme et
|
||||
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,
|
||||
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
|
||||
README d'origine de kitty et `RACCOURCIS-CLAVIER.md` liste tous les raccourcis
|
||||
actifs par défaut, sans configuration.
|
||||
|
||||
## Contenu de la branche `feat/file-manager-panel`
|
||||
|
||||
| Chemin | Rôle |
|
||||
| --- | --- |
|
||||
| `kittens/file_manager/main.go` | Interface du panneau (rendu, touches, souris, actions fichiers) |
|
||||
| `kittens/file_manager/main.py` | Définition des options, des raccourcis et du résultat renvoyé au shell |
|
||||
| `kittens/file_manager/main_test.go` | Tests unitaires des fonctions pures |
|
||||
| `kittens/file_manager/cli_generated.go`, `conf_generated.go` | Générés à la compilation, **non versionnés** |
|
||||
| `tools/cmd/tool/main.go` | Enregistre `kitten file-manager` dans le binaire `kitten` |
|
||||
| `docs/kittens/file-manager.rst` | Documentation utilisateur du panneau |
|
||||
| `packaging/PKGBUILD`, `packaging/README.md` | Paquet pacman `fws-kitty` |
|
||||
|
||||
Les fichiers `*_generated.go` sont listés dans `.gitignore` : ils sont produits
|
||||
par le code de génération à chaque `./dev.sh build`. Un `go build ./...` lancé
|
||||
avant cette étape échoue avec `undefined: create_cmd` ou `undefined: Options`,
|
||||
c'est normal.
|
||||
|
||||
## Prérequis
|
||||
|
||||
- **Linux x86_64 ou aarch64** (Arch Linux recommandé : c'est la cible du fork).
|
||||
Windows et macOS ne compilent pas nativement, voir la section Docker.
|
||||
- **Python >= 3.12** (voir `pyproject.toml`).
|
||||
- **Go >= 1.26** (voir `go.mod`).
|
||||
- Un serveur graphique X11 ou Wayland : le panneau s'affiche dans une fenêtre
|
||||
kitty, il n'existe pas de mode texte seul.
|
||||
|
||||
Sur Arch Linux, tous les paquets de compilation :
|
||||
|
||||
```sh
|
||||
sudo pacman -S --needed base-devel git go python \
|
||||
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 rsync which file
|
||||
```
|
||||
|
||||
Pour le paquet Arch, `makepkg` a besoin en plus de `pkgconf` et `ncurses`.
|
||||
|
||||
## Récupérer le code
|
||||
|
||||
```sh
|
||||
git clone <url-du-depot> FWS-Kitty
|
||||
cd FWS-Kitty
|
||||
git checkout feat/file-manager-panel
|
||||
git pull
|
||||
```
|
||||
|
||||
Le dépôt est normalisé en **LF** par `.gitattributes`. Si vous voyez des erreurs
|
||||
du type `dev.sh: $'\r': command not found`, corrigez la copie de travail :
|
||||
|
||||
```sh
|
||||
git config core.autocrlf false
|
||||
git rm --cached -r -q . && git reset --hard
|
||||
```
|
||||
|
||||
`packaging/` doit être présent après le `git pull` : sans lui, la section
|
||||
« Paquet Arch » est impossible. Si le dossier manque, la branche n'a pas été
|
||||
poussée complètement.
|
||||
|
||||
## Compiler
|
||||
|
||||
Tout passe par `./dev.sh`, qui télécharge un bundle de dépendances précompilées
|
||||
(Python, pkg-config, Sphinx, polices…) dans `dependencies/`, puis appelle
|
||||
`setup.py`.
|
||||
|
||||
```sh
|
||||
./dev.sh deps # une seule fois, ou après une erreur de dépendances
|
||||
./dev.sh build
|
||||
```
|
||||
|
||||
`./dev.sh build` compile le C, génère le code Go (dont la configuration et la
|
||||
ligne de commande du gestionnaire de fichiers), puis compile les kittens et les
|
||||
outils. Les binaires finaux sont :
|
||||
|
||||
```sh
|
||||
kitty/launcher/kitty # le terminal
|
||||
kitty/launcher/kitten # le lanceur de kittens (dont file-manager)
|
||||
```
|
||||
|
||||
Options utiles :
|
||||
|
||||
```sh
|
||||
./dev.sh build --debug # symboles de debug
|
||||
./dev.sh build --debug --sanitize
|
||||
./dev.sh build -h # toutes les options
|
||||
```
|
||||
|
||||
`dependencies/` est local et ignoré par git : il n'est jamais récupéré par un
|
||||
`git pull`, et il peut exister sous forme de simple archive téléchargée. Depuis
|
||||
cette version, `build` vérifie la présence du Python du bundle et relance
|
||||
automatiquement `deps` s'il manque. En cas de doute :
|
||||
|
||||
```sh
|
||||
rm -rf dependencies
|
||||
./dev.sh deps && ./dev.sh build
|
||||
```
|
||||
|
||||
Pour lancer les binaires sans chemin complet, ajoutez `kitty/launcher` au
|
||||
`PATH`, ou créez des liens symboliques :
|
||||
|
||||
```sh
|
||||
ln -s "$PWD/kitty/launcher/kitty" ~/.local/bin/kitty
|
||||
ln -s "$PWD/kitty/launcher/kitten" ~/.local/bin/kitten
|
||||
```
|
||||
|
||||
Le binaire retrouve ses sources par le chemin où `./dev.sh build` a été lancé :
|
||||
si le dossier est déplacé, faites `make clean && ./dev.sh build`.
|
||||
|
||||
## Lancer kitty
|
||||
|
||||
```sh
|
||||
./kitty/launcher/kitty
|
||||
```
|
||||
|
||||
Vérification rapide sans interface graphique :
|
||||
|
||||
```sh
|
||||
./kitty/launcher/kitty --version # kitty 0.50.0 ...
|
||||
./kitty/launcher/kitten --version # kitten 0.50.0 ...
|
||||
```
|
||||
|
||||
Sous WSL2, activez WSLg (Windows 11) pour obtenir une fenêtre, sinon exportez un
|
||||
`DISPLAY` vers un serveur X. Dans un conteneur, montez le socket X11 ou le
|
||||
socket Wayland ; une image sans affichage ne peut pas montrer le panneau.
|
||||
|
||||
### Docker (depuis Windows ou macOS)
|
||||
|
||||
`Dockerfile.arch` fournit un Arch Linux avec toutes les dépendances :
|
||||
|
||||
```sh
|
||||
docker build -f Dockerfile.arch -t kitty-arch-dev .
|
||||
docker run --rm -v "$PWD:/src" -w /src kitty-arch-dev sh dev.sh build
|
||||
docker run --rm -it -v "$PWD:/src" -w /src kitty-arch-dev ./kitty/launcher/kitty
|
||||
```
|
||||
|
||||
Sous Git Bash, préfixez par `MSYS_NO_PATHCONV=1` pour que `/src` ne soit pas
|
||||
réécrit en chemin Windows. Le conteneur n'a pas d'affichage par défaut.
|
||||
|
||||
## Utiliser l'explorateur de fichiers
|
||||
|
||||
Le panneau doit tourner **dans kitty** : c'est un kitten, pas un programme
|
||||
autonome. Depuis un shell lancé dans kitty :
|
||||
|
||||
```sh
|
||||
kitten file-manager # répertoire courant
|
||||
kitten file-manager ~/Projets # répertoire de départ
|
||||
kitten file-manager --show-hidden
|
||||
```
|
||||
|
||||
`Ctrl+Shift+E` ouvre le panneau par défaut, dans un dock latéral gauche. Pour
|
||||
remplacer ce comportement, redéfinissez le raccourci dans
|
||||
`~/.config/kitty/kitty.conf` :
|
||||
|
||||
```conf
|
||||
map ctrl+shift+e launch --type=overlay kitten file-manager
|
||||
```
|
||||
|
||||
Un fichier validé s'ouvre dans un nouvel onglet, donc en pleine fenêtre même
|
||||
depuis un dock, et le panneau reprend la main à la fermeture de l'éditeur. En
|
||||
revanche, kitty ne rend jamais le résultat d'un `launch --type=window-dock` au
|
||||
shell : `Ctrl+Entrée` dans un dock ne peut donc pas faire de `cd`.
|
||||
|
||||
### Raccourcis par défaut
|
||||
|
||||
| Touche | Action |
|
||||
| --- | --- |
|
||||
| `Entrée` | Ouvre la sélection : entre dans le répertoire, ou ouvre le fichier dans l'éditeur dans un nouvel onglet ; le panneau revient à la fermeture de l'éditeur |
|
||||
| `→` / `L` | Entre dans le répertoire sélectionné sans toucher au shell |
|
||||
| `←` / `Retour arrière` / `H` | Remonte au répertoire parent |
|
||||
| `Ctrl+Entrée` / `C` | Déplace le shell vers le répertoire affiché, sans tenir compte de la sélection |
|
||||
| `/` | Filtre la liste par recherche floue ; `Entrée` ouvre la sélection, `Échap` efface la requête |
|
||||
| `:` | Ouvre la palette des actions, filtrable, `Entrée` exécute l'action |
|
||||
| `O` / `T` | Ouvre le fichier sélectionné dans un nouvel onglet / une nouvelle fenêtre |
|
||||
| `A` | Alias de `Maj+N` : crée un répertoire |
|
||||
| `↑` / `K`, `↓` / `J` | Déplace la sélection |
|
||||
| `Page préc.` / `Ctrl+B`, `Page suiv.` / `Ctrl+F` | Déplace la sélection d'une page |
|
||||
| `Début` / `G`, `Fin` / `Maj+G` | Première / dernière entrée |
|
||||
| `N` | Crée un fichier (nom saisi dans la ligne d'état) |
|
||||
| `Maj+N` | Crée un répertoire |
|
||||
| `R` | Renomme l'entrée sélectionnée |
|
||||
| `D` | Supprime 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` / `Q` | Ferme sans rien changer |
|
||||
|
||||
Un clic gauche sélectionne une entrée. Tous les raccourcis sont redéfinissables.
|
||||
|
||||
### Limites à connaître
|
||||
|
||||
- `Entrée` reste dans le panneau et fonctionne partout, dock compris.
|
||||
`Ctrl+Entrée` agit sur la fenêtre qui a lancé le panneau : dans un dock ou un
|
||||
panneau du bureau, le changement de répertoire n'a personne à qui s'appliquer,
|
||||
lancez l'explorateur depuis un shell pour `cd`.
|
||||
- L'éditeur s'ouvre toujours dans un nouvel onglet, plein écran ; fermer
|
||||
l'éditeur referme l'onglet et rend le panneau tel qu'il était.
|
||||
- L'édition passe par kitty : le fichier doit être accessible en lecture et en
|
||||
écriture. Pour un fichier de root, utilisez `sudo -e` depuis le shell.
|
||||
- La suppression d'un répertoire non vide affiche une erreur, jamais une
|
||||
suppression récursive.
|
||||
|
||||
## Configurer l'explorateur
|
||||
|
||||
Les réglages vivent dans `~/.config/kitty/file-manager.conf` (même syntaxe que
|
||||
`kitty.conf`) :
|
||||
|
||||
```conf
|
||||
# Afficher les fichiers cachés à l'ouverture
|
||||
show_hidden yes
|
||||
|
||||
# name (défaut), mtime (plus récent d'abord) ou size (plus gros d'abord)
|
||||
sort_by mtime
|
||||
|
||||
# Remplacer un raccourci
|
||||
map toggle_hidden ctrl+h toggle_hidden
|
||||
map delete x delete
|
||||
```
|
||||
|
||||
Actions disponibles : `quit`, `move_up`, `move_down`, `page_up`, `page_down`,
|
||||
`home`, `end`, `activate`, `enter_dir`, `parent_dir`, `cd_here`,
|
||||
`toggle_hidden`, `create_file`, `create_dir`, `rename`, `delete`, `copy_path`,
|
||||
`refresh`.
|
||||
|
||||
L'éditeur est celui de kitty : l'option `editor` de `kitty.conf`, ou `VISUAL`
|
||||
puis `EDITOR` quand elle vaut `.` (le défaut). Pour forcer nano, mettez
|
||||
`editor nano` dans `kitty.conf`, pas dans `file-manager.conf`.
|
||||
|
||||
## Tester et vérifier
|
||||
|
||||
```sh
|
||||
./test.py # suite complète (Python + Go)
|
||||
./test.py --module kittens/file_manager # tests Go du panneau
|
||||
./test.py TestTruncateToWidth # un test Go nommé
|
||||
./test.py type-check # vérification de types
|
||||
ruff check --fix # lint Python
|
||||
```
|
||||
|
||||
Sans passer par `test.py`, les tests Go du panneau se lancent directement :
|
||||
|
||||
```sh
|
||||
go test ./kittens/file_manager/
|
||||
```
|
||||
|
||||
Après une modification du Go ou du Python du kitten, `./dev.sh build` est
|
||||
obligatoire : c'est lui qui régénère `cli_generated.go` / `conf_generated.go`
|
||||
et réinstalle les modules Python du panneau.
|
||||
|
||||
## Construire la documentation
|
||||
|
||||
La documentation HTML et les pages de manuel demandent Sphinx :
|
||||
|
||||
```sh
|
||||
./dev.sh deps --for-docs
|
||||
./dev.sh docs
|
||||
```
|
||||
|
||||
La page `docs/kittens/file-manager.rst` est incluse par le motif `kittens/*` du
|
||||
sommaire (`docs/kittens_intro.rst`) et embarque les options générées.
|
||||
|
||||
## Paquet Arch
|
||||
|
||||
```sh
|
||||
cd packaging
|
||||
makepkg -f # -s pour installer les dépendances manquantes
|
||||
```
|
||||
|
||||
Le résultat est `fws-kitty-<version>-<rel>-<arch>.pkg.tar.zst`. Le paquet
|
||||
s'appelle `fws-kitty`, remplace `kitty` via `provides`/`conflicts` et installe
|
||||
les binaires dans `/usr/bin`.
|
||||
|
||||
```sh
|
||||
sudo pacman -U fws-kitty-*.pkg.tar.zst
|
||||
kitty --version
|
||||
kitten --version
|
||||
kitten file-manager --help
|
||||
```
|
||||
|
||||
`makepkg` construit depuis la branche `_branch` du `PKGBUILD` (`main` par
|
||||
défaut). Pour empaqueter cette branche avant fusion, modifiez la ligne en haut
|
||||
du fichier (une variable d'environnement ne suffit pas, le `PKGBUILD`
|
||||
réaffecte `_branch`) :
|
||||
|
||||
```sh
|
||||
_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,
|
||||
automatisation) est détaillée dans `packaging/README.md`.
|
||||
|
||||
## Dépannage
|
||||
|
||||
| Symptôme | Cause et solution |
|
||||
| --- | --- |
|
||||
| `fork/exec .../dependencies/linux-amd64/bin/python: no such file or directory` | Bundle de dépendances incomplet. `build` le détecte maintenant et relance `deps` ; sinon `rm -rf dependencies && ./dev.sh deps`. |
|
||||
| `undefined: create_cmd`, `undefined: Options`, `undefined: NewConfig` | Code Go généré absent (fichiers ignorés par git). Lancer `./dev.sh build`, pas `go build ./...`. |
|
||||
| `Unknown kitten: file-manager` ou l'aide ne le liste pas | Binaire `kitten` obsolète : relancer `./dev.sh build` et utiliser `kitty/launcher/kitten`. |
|
||||
| `+file-manager is not a known kitten` | Le panneau s'appelle `kitten file-manager` (sans `+`). |
|
||||
| `kitten: command not found` | Les binaires sont dans `kitty/launcher/` : chemin complet, `PATH` ou lien symbolique. |
|
||||
| `Ctrl+Entrée` ferme le panneau sans changer de répertoire | Lancé dans un dock : `cd` n'a pas de shell cible. Lancer l'explorateur depuis une fenêtre de shell. |
|
||||
| `... is not readable and writeable` en ouvrant un fichier | L'édition passe par kitty et demande un accès en lecture et écriture. Ouvrir le fichier avec `sudo -e` depuis le shell. |
|
||||
| Rien ne s'affiche / pas de fenêtre | Pas de serveur graphique : session X11/Wayland, WSLg, ou socket monté dans Docker. |
|
||||
| `X11/extensions/XInput2.h: No such file` | Installer `libxi` (XInput2). |
|
||||
| `dev.sh: $'\r': command not found` | Fins de ligne CRLF, voir « Récupérer le code ». |
|
||||
| Compilation très lente sous Windows | Montage Docker depuis `C:` : préférer un Arch natif, WSL2 ou un volume local. |
|
||||
| `error: failed to init transaction (unable to lock database)` avec `makepkg -s` | Un autre pacman tourne, ou utilisez `makepkg -f --nodeps` avec les dépendances déjà installées. |
|
||||
|
||||
### Vérifier que la branche est complète
|
||||
|
||||
```sh
|
||||
git status --short # doit être vide (ou seulement des artefacts ignorés)
|
||||
git ls-files packaging # doit lister PKGBUILD et README.md
|
||||
./dev.sh build
|
||||
./test.py --module kittens/file_manager
|
||||
./kitty/launcher/kitten file-manager --help
|
||||
```
|
||||
|
||||
`packaging/` est actuellement **non versionné** : tant qu'il n'est pas commité
|
||||
et poussé, un `git pull` sur une autre machine ne le récupère pas.
|
||||
|
||||
## Organisation du dépôt
|
||||
|
||||
| Dossier | Contenu |
|
||||
| --- | --- |
|
||||
| `kitty/` | Cœur du terminal (C, Python) |
|
||||
| `kittens/` | Kittens intégrés, dont `file_manager/` |
|
||||
| `tools/` | Outils Go (`kitten`, `kitty`, complétion) |
|
||||
| `glfw/`, `glad/`, `3rdparty/` | Fenêtrage et dépendances embarquées |
|
||||
| `docs/` | Documentation Sphinx (FR) |
|
||||
| `gen/`, `bypy/` | Génération de code et scripts de build |
|
||||
| `packaging/` | Paquet Arch |
|
||||
| `kitty_tests/` | Tests Python |
|
||||
|
||||
Licence : GPL-3.0-only (`LICENSE`).
|
||||
+23
-16
@@ -14,7 +14,6 @@ import (
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"runtime"
|
||||
"strings"
|
||||
)
|
||||
@@ -269,18 +268,11 @@ func dependencies(args []string) {
|
||||
fmt.Println("Dependencies needed to generate documentation have been installed. Build docs with ./dev.sh docs")
|
||||
exit(0)
|
||||
}
|
||||
data, err := os.ReadFile(".github/workflows/ci.py")
|
||||
if err != nil {
|
||||
exit(err)
|
||||
}
|
||||
pat := regexp.MustCompile("BUNDLE_URL = '(.+?)'")
|
||||
// The upstream CI scripts are not vendored here, so pin the bundle URL
|
||||
// instead of scraping it from .github/workflows/ci.py.
|
||||
const bundle_url = "https://download.calibre-ebook.com/ci/kitty/{}-64.tar.xz"
|
||||
prefix := "/sw/sw"
|
||||
var url string
|
||||
if m := pat.FindStringSubmatch(string(data)); len(m) < 2 {
|
||||
exit("Failed to find BUNDLE_URL in ci.py")
|
||||
} else {
|
||||
url = m[1]
|
||||
}
|
||||
url := bundle_url
|
||||
var which string
|
||||
switch runtime.GOOS {
|
||||
case "darwin":
|
||||
@@ -308,6 +300,7 @@ func dependencies(args []string) {
|
||||
}
|
||||
tarfile, _ := filepath.Abs(cached_download(url))
|
||||
root := root_dir()
|
||||
var err error
|
||||
if err := os.MkdirAll(root, 0o755); err != nil {
|
||||
exit(err)
|
||||
}
|
||||
@@ -374,6 +367,18 @@ func prepend(env_var, path string) {
|
||||
os.Setenv(env_var, path+val)
|
||||
}
|
||||
|
||||
func python_exe() string {
|
||||
switch runtime.GOOS {
|
||||
case "linux":
|
||||
return filepath.Join(root_dir(), "bin", "python")
|
||||
case `darwin`:
|
||||
return filepath.Join(root_dir(), macos_python)
|
||||
default:
|
||||
exit("Building is only supported on Linux and macOS")
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func setup_to_run_python() (python string) {
|
||||
root := root_dir()
|
||||
for _, x := range os.Environ() {
|
||||
@@ -386,18 +391,20 @@ func setup_to_run_python() (python string) {
|
||||
case "linux":
|
||||
prepend("LD_LIBRARY_PATH", filepath.Join(root, "lib"))
|
||||
os.Setenv("PYTHONHOME", root)
|
||||
python = filepath.Join(root, "bin", "python")
|
||||
case `darwin`:
|
||||
python = filepath.Join(root, macos_python)
|
||||
default:
|
||||
exit("Building is only supported on Linux and macOS")
|
||||
}
|
||||
return
|
||||
return python_exe()
|
||||
}
|
||||
|
||||
func build(args []string) {
|
||||
chdir_to_base()
|
||||
if _, err := os.Stat(folder); err != nil {
|
||||
// Check the Python binary instead of the dependencies folder: the folder
|
||||
// survives a git pull (it is gitignored, so a clone has none) but can
|
||||
// contain only the cached tarball, which used to fail later with a
|
||||
// cryptic missing Python error instead of downloading the bundle.
|
||||
if _, err := os.Stat(python_exe()); err != nil {
|
||||
dependencies(nil)
|
||||
}
|
||||
root := root_dir()
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
# 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).
|
||||
@@ -0,0 +1,291 @@
|
||||
# É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 }})\"}"
|
||||
@@ -0,0 +1,216 @@
|
||||
# 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"
|
||||
```
|
||||
@@ -0,0 +1,142 @@
|
||||
# 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`.
|
||||
+5
-2
@@ -16,9 +16,12 @@ override OPTS=
|
||||
endif
|
||||
|
||||
# You can set these variables from the command line.
|
||||
# Prefer the tool environment kept at the root of the checkout, so that the
|
||||
# documentation builds without installing its extensions system-wide.
|
||||
VENV ?= ../.venv
|
||||
SPHINXOPTS = -n -q -j auto -T $(FAIL_WARN) $(OPTS)
|
||||
SPHINXBUILD = sphinx-build
|
||||
SPHINXAUTOBUILD = sphinx-autobuild
|
||||
SPHINXBUILD ?= $(if $(wildcard $(VENV)/bin/sphinx-build),$(VENV)/bin/sphinx-build,sphinx-build)
|
||||
SPHINXAUTOBUILD ?= $(if $(wildcard $(VENV)/bin/sphinx-autobuild),$(VENV)/bin/sphinx-autobuild,sphinx-autobuild)
|
||||
SPHINXPROJ = kitty
|
||||
SOURCEDIR = .
|
||||
BUILDDIR = _build
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
.. _accessibility:
|
||||
|
||||
Accessibilité
|
||||
=============
|
||||
|
||||
|kitty| se pilote entièrement au clavier et son mode fort contraste garantit un
|
||||
rapport de contraste d'au moins :code:`4.5:1`, le seuil du niveau AA des
|
||||
:link:`WCAG <https://en.wikipedia.org/wiki/Web_Content_Accessibility_Guidelines>`.
|
||||
La navigation fonctionne sans réglage : les raccourcis décrits ici sont ceux par
|
||||
défaut.
|
||||
|
||||
Navigation clavier par défaut
|
||||
-----------------------------
|
||||
|
||||
Tous les kittens interactifs acceptent la tabulation, les flèches, :kbd:`Entrée`
|
||||
et :kbd:`Échap`. Aucune configuration n'est nécessaire : les raccourcis sont
|
||||
livrés avec |kitty| et restent actifs même sans :file:`kitty.conf`.
|
||||
|
||||
.. list-table::
|
||||
:header-rows: 1
|
||||
:widths: auto
|
||||
|
||||
* - Interface
|
||||
- Ouverture par défaut
|
||||
- Navigation
|
||||
* - :doc:`Gestionnaire de fichiers </kittens/file-manager>`
|
||||
- :kbd:`Ctrl+Shift+E`
|
||||
- :kbd:`Tab` / :kbd:`Maj+Tab`, :kbd:`↓` / :kbd:`↑`, :kbd:`Page↓` /
|
||||
:kbd:`Page↑`, :kbd:`Début` / :kbd:`Fin`, :kbd:`Entrée`, :kbd:`Échap`
|
||||
* - :doc:`Palette de commandes </kittens/command-palette>`
|
||||
- :kbd:`Ctrl+Shift+F3`
|
||||
- :kbd:`Tab` / :kbd:`Maj+Tab`, :kbd:`↓` / :kbd:`↑`, :kbd:`Page↓` /
|
||||
:kbd:`Page↑`, :kbd:`Début` / :kbd:`Fin`, :kbd:`Entrée`, :kbd:`Échap`
|
||||
* - :doc:`Saisie Unicode </kittens/unicode_input>`
|
||||
- :kbd:`Ctrl+Shift+U`
|
||||
- :kbd:`Tab` / :kbd:`Maj+Tab` (changement de zone), flèches,
|
||||
:kbd:`Entrée`, :kbd:`Échap`
|
||||
|
||||
Les autres kittens interactifs (:doc:`thèmes </kittens/themes>`,
|
||||
:doc:`choix des polices </kittens/choose-fonts>`, :doc:`diff </kittens/diff>`,
|
||||
:doc:`hints </kittens/hints>`) suivent la même convention : les flèches
|
||||
parcourent les listes, :kbd:`Entrée` valide et :kbd:`Échap` annule. Le détail
|
||||
des touches propres à chaque kitten figure dans sa page de documentation.
|
||||
|
||||
Raccourcis configurables
|
||||
------------------------
|
||||
|
||||
Les raccourcis par défaut ne sont qu'un point de départ. Ils se redéfinissent
|
||||
dans :file:`kitty.conf` pour les actions de |kitty| et dans
|
||||
:file:`file-manager.conf` pour le panneau, sans toucher aux valeurs par défaut
|
||||
du programme. Par exemple, pour remplacer la tabulation par :kbd:`J` / :kbd:`K`
|
||||
dans le panneau :
|
||||
|
||||
.. code-block:: conf
|
||||
|
||||
# ~/.config/kitty/file-manager.conf
|
||||
map move_up k move_up
|
||||
map move_down j move_down
|
||||
|
||||
Le raccourci d'ouverture se change lui aussi :
|
||||
|
||||
.. code-block:: conf
|
||||
|
||||
# ~/.config/kitty/kitty.conf
|
||||
map ctrl+shift+e launch --type=overlay kitten file-manager
|
||||
|
||||
Mode fort contraste
|
||||
-------------------
|
||||
|
||||
|kitty| intègre un mode qui garantit le contraste entre le texte et le fond,
|
||||
sans changer la teinte des couleurs. Il s'active avec
|
||||
:opt:`text_fg_override_threshold` et le seuil de contraste voulu :
|
||||
|
||||
.. code-block:: conf
|
||||
|
||||
text_fg_override_threshold 4.5 ratio
|
||||
|
||||
La valeur :code:`ratio` est comparée au rapport de contraste WCAG et va de
|
||||
:code:`0.0 ratio` à :code:`21.0 ratio`. Le réglage n'agit que sur les couleurs
|
||||
de premier plan : une couleur trop proche du fond est éclaircie ou assombrie
|
||||
autant que nécessaire, en conservant sa teinte et sa saturation. Pour une
|
||||
lisibilité maximale, on peut aussi choisir une palette explicite :
|
||||
|
||||
.. code-block:: conf
|
||||
|
||||
foreground #ffffff
|
||||
background #000000
|
||||
|
||||
Mesures des rapports de contraste (formule WCAG 2.1, luminance relative) :
|
||||
|
||||
.. list-table::
|
||||
:header-rows: 1
|
||||
:widths: auto
|
||||
|
||||
* - Texte
|
||||
- Fond
|
||||
- Rapport
|
||||
* - :code:`#ffffff`
|
||||
- :code:`#000000`
|
||||
- :code:`21.0:1` (niveau AAA)
|
||||
* - :code:`#f8f8f2`
|
||||
- :code:`#111111`
|
||||
- :code:`17.7:1` (niveau AAA)
|
||||
* - :code:`#dddddd`
|
||||
- :code:`#111111`
|
||||
- :code:`13.9:1` (niveau AAA)
|
||||
|
||||
Le seuil :code:`4.5 ratio` suffit donc pour le niveau AA quelle que soit la
|
||||
palette, et ces trois combinaisons dépassent largement le niveau AAA.
|
||||
|
||||
.. note::
|
||||
|
||||
Certains programmes dessinent des graphismes avec des caractères de bloc en
|
||||
mettant volontairement le texte et le fond de la même couleur. Le mode
|
||||
:code:`ratio` conserve alors la teinte ; si un affichage paraît rayé ou
|
||||
décoloré, préférez-le au mode :code:`%`, qui force le premier plan en blanc
|
||||
ou en noir et peut casser ces graphismes.
|
||||
|
||||
Aucune régression par défaut
|
||||
----------------------------
|
||||
|
||||
Le mode fort contraste est désactivé par défaut
|
||||
(:opt:`text_fg_override_threshold` vaut :code:`0`) et la palette reste celle de
|
||||
l'utilisateur. Les raccourcis ajoutés sont de nouvelles touches : les flèches et
|
||||
les touches existantes continuent de fonctionner, et les captures d'écran par
|
||||
défaut sont inchangées. Le mode ne s'active qu'en ajoutant la ligne
|
||||
:code:`text_fg_override_threshold 4.5 ratio` à :file:`kitty.conf`.
|
||||
+30
-15
@@ -12,21 +12,36 @@ window manager. The keyboard controls (which are :ref:`all customizable
|
||||
Scrolling
|
||||
~~~~~~~~~~~~~~
|
||||
|
||||
========================= =======================
|
||||
Action Shortcut
|
||||
========================= =======================
|
||||
Line up :sc:`scroll_line_up` (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 down :sc:`scroll_page_down` (also :kbd:`⌘+⇟` on macOS)
|
||||
Top :sc:`scroll_home` (also :kbd:`⌘+↖` on macOS)
|
||||
Bottom :sc:`scroll_end` (also :kbd:`⌘+↘` on macOS)
|
||||
Previous shell prompt :sc:`scroll_to_previous_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 last cmd output :sc:`show_last_command_output` (see :ref:`shell_integration`)
|
||||
Search scrollback in less :sc:`search_scrollback` (also :kbd:`⌘+F` on macOS)
|
||||
========================= =======================
|
||||
========================== =======================
|
||||
Action Shortcut
|
||||
========================== =======================
|
||||
Line up :sc:`scroll_line_up` (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 down :sc:`scroll_page_down` (also :kbd:`⌘+⇟` on macOS)
|
||||
Top :sc:`scroll_home` (also :kbd:`⌘+↖` on macOS)
|
||||
Bottom :sc:`scroll_end` (also :kbd:`⌘+↘` on macOS)
|
||||
Previous shell prompt :sc:`scroll_to_previous_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 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 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.
|
||||
When the alternate screen is active (for example when using a full screen
|
||||
|
||||
+67
-58
@@ -1,125 +1,133 @@
|
||||
Install kitty
|
||||
Installer kitty
|
||||
========================
|
||||
|
||||
Binary install
|
||||
----------------
|
||||
Installation des binaires
|
||||
-------------------------
|
||||
|
||||
.. highlight:: sh
|
||||
|
||||
You can install pre-built binaries of |kitty| if you are on macOS or Linux using
|
||||
the following simple command:
|
||||
Vous pouvez installer des binaires précompilés de |kitty| sous macOS ou Linux
|
||||
avec la commande simple suivante :
|
||||
|
||||
.. code-block:: sh
|
||||
|
||||
_kitty_install_cmd
|
||||
|
||||
|
||||
The binaries will be installed in the standard location for your OS,
|
||||
:file:`/Applications/kitty.app` on macOS and :file:`~/.local/kitty.app` on
|
||||
Linux. The installer only touches files in that directory. To update kitty,
|
||||
simply re-run the command.
|
||||
Les binaires seront installés à l'emplacement standard de votre système,
|
||||
:file:`/Applications/kitty.app` sous macOS et :file:`~/.local/kitty.app` sous
|
||||
Linux. L'installateur ne touche qu'aux fichiers de ce répertoire. Pour mettre à
|
||||
jour kitty, il suffit de relancer la commande.
|
||||
|
||||
.. warning::
|
||||
**Do not** copy the kitty binary out of the installation folder. If you want
|
||||
to add it to your :envvar:`PATH`, create a symlink in :file:`~/.local/bin` or
|
||||
:file:`/usr/bin` or wherever. You should create a symlink for the :file:`kitten`
|
||||
binary as well. Whichever folder you choose to create the symlink in should
|
||||
be in the **systemwide** PATH, a folder added to the PATH in your shell rc
|
||||
files will not work when running kitty from your desktop environment.
|
||||
**Ne copiez pas** le binaire kitty en dehors du dossier d'installation. Si
|
||||
vous voulez l'ajouter à votre :envvar:`PATH`, créez un lien symbolique dans
|
||||
:file:`~/.local/bin` ou :file:`/usr/bin` ou ailleurs. Vous devriez aussi
|
||||
créer un lien symbolique pour le binaire :file:`kitten`. Le dossier dans
|
||||
lequel vous créez le lien symbolique doit se trouver dans le PATH
|
||||
**système** : un dossier ajouté au PATH depuis les fichiers rc de votre
|
||||
shell ne fonctionnera pas lorsque kitty est lancé depuis votre
|
||||
environnement de bureau.
|
||||
|
||||
|
||||
Manually installing
|
||||
Installation manuelle
|
||||
---------------------
|
||||
|
||||
If something goes wrong or you simply do not want to run the installer, you can
|
||||
manually download and install |kitty| from the `GitHub releases page
|
||||
<https://github.com/kovidgoyal/kitty/releases>`__. If you are on macOS, download
|
||||
the :file:`.dmg` and install as normal. If you are on Linux, download the
|
||||
tarball and extract it into a directory. The |kitty| executable will be in the
|
||||
:file:`bin` sub-directory.
|
||||
Si quelque chose se passe mal ou si vous ne voulez simplement pas exécuter
|
||||
l'installateur, vous pouvez télécharger et installer |kitty| manuellement
|
||||
depuis la `page des versions GitHub
|
||||
<https://github.com/kovidgoyal/kitty/releases>`__. Sous macOS, téléchargez le
|
||||
:file:`.dmg` et installez-le normalement. Sous Linux, téléchargez l'archive
|
||||
tar et extrayez-la dans un dossier. L'exécutable |kitty| se trouvera dans le
|
||||
sous-dossier :file:`bin`.
|
||||
|
||||
|
||||
Desktop integration on Linux
|
||||
Intégration au bureau sous Linux
|
||||
--------------------------------
|
||||
|
||||
If you want the kitty icon to appear in the taskbar and an entry for it to be
|
||||
present in the menus, you will need to install the :file:`kitty.desktop` file.
|
||||
The details of the following procedure may need to be adjusted for your
|
||||
particular desktop, but it should work for most major desktop environments.
|
||||
Si vous voulez que l'icône de kitty apparaisse dans la barre des tâches et
|
||||
qu'une entrée soit présente dans les menus, vous devrez installer le fichier
|
||||
:file:`kitty.desktop`. Les détails de la procédure suivante peuvent devoir être
|
||||
adaptés à votre bureau, mais elle devrait fonctionner pour la plupart des
|
||||
environnements de bureau majeurs.
|
||||
|
||||
.. code-block:: sh
|
||||
|
||||
# Create symbolic links to add kitty and kitten to PATH (assuming ~/.local/bin is in
|
||||
# your system-wide PATH)
|
||||
# Crée des liens symboliques pour ajouter kitty et kitten au PATH (en supposant que ~/.local/bin
|
||||
# se trouve dans votre PATH système)
|
||||
ln -sf ~/.local/kitty.app/bin/kitty ~/.local/kitty.app/bin/kitten ~/.local/bin/
|
||||
# Place the kitty.desktop file somewhere it can be found by the OS
|
||||
# Place le fichier kitty.desktop là où le système peut le trouver
|
||||
cp ~/.local/kitty.app/share/applications/kitty.desktop ~/.local/share/applications/
|
||||
# If you want to open text files and images in kitty via your file manager also add the kitty-open.desktop file
|
||||
# Si vous voulez ouvrir des fichiers texte et des images dans kitty depuis votre gestionnaire de
|
||||
# fichiers, ajoutez aussi le fichier kitty-open.desktop
|
||||
cp ~/.local/kitty.app/share/applications/kitty-open.desktop ~/.local/share/applications/
|
||||
# Update the paths to the kitty and its icon in the kitty desktop file(s)
|
||||
# Met à jour les chemins vers kitty et son icône dans le(s) fichier(s) desktop de kitty
|
||||
sed -i "s|Icon=kitty|Icon=$(readlink -f ~)/.local/kitty.app/share/icons/hicolor/256x256/apps/kitty.png|g" ~/.local/share/applications/kitty*.desktop
|
||||
sed -i "s|Exec=kitty|Exec=$(readlink -f ~)/.local/kitty.app/bin/kitty|g" ~/.local/share/applications/kitty*.desktop
|
||||
# Make xdg-terminal-exec (and hence desktop environments that support it use kitty)
|
||||
# Fait de xdg-terminal-exec (et donc des environnements de bureau qui le prennent en charge) kitty
|
||||
echo 'kitty.desktop' > ~/.config/xdg-terminals.list
|
||||
|
||||
.. note::
|
||||
In :file:`kitty-open.desktop`, kitty is registered to handle some supported
|
||||
MIME types. This will cause kitty to take precedence on some systems where
|
||||
the default apps are not explicitly set. For example, if you expect to use
|
||||
other GUI file managers to open dir paths when using commands such as
|
||||
:program:`xdg-open`, you should configure the default opener for the MIME
|
||||
type ``inode/directory``::
|
||||
Dans :file:`kitty-open.desktop`, kitty est enregistré pour gérer certains
|
||||
types MIME pris en charge. Cela fera en sorte que kitty soit prioritaire
|
||||
sur certains systèmes où les applications par défaut ne sont pas
|
||||
explicitement définies. Par exemple, si vous comptez utiliser d'autres
|
||||
gestionnaires de fichiers graphiques pour ouvrir des chemins de dossier
|
||||
avec des commandes comme :program:`xdg-open`, vous devriez configurer
|
||||
l'ouvreur par défaut du type MIME ``inode/directory`` ::
|
||||
|
||||
xdg-mime default org.kde.dolphin.desktop inode/directory
|
||||
|
||||
.. note::
|
||||
If you use the venerable `stow <https://www.gnu.org/software/stow/>`__
|
||||
command to manage your manual installations, the following takes care of the
|
||||
above for you (use with :code:`dest=~/.local/stow`)::
|
||||
Si vous utilisez la vénérable commande `stow
|
||||
<https://www.gnu.org/software/stow/>`__ pour gérer vos installations
|
||||
manuelles, ce qui suit s'occupe de tout ce qui précède à votre place
|
||||
(à utiliser avec :code:`dest=~/.local/stow`) ::
|
||||
|
||||
cd ~/.local/stow
|
||||
stow -v kitty.app
|
||||
|
||||
|
||||
Customizing the installation
|
||||
Personnaliser l'installation
|
||||
--------------------------------
|
||||
|
||||
.. _nightly:
|
||||
|
||||
* You can install the latest nightly kitty build with ``installer``:
|
||||
* Vous pouvez installer la dernière version nightly de kitty avec
|
||||
``installer`` :
|
||||
|
||||
.. code-block:: sh
|
||||
|
||||
_kitty_install_cmd \
|
||||
installer=nightly
|
||||
|
||||
Nightly builds show the date and hash of the commit they were built from in
|
||||
the output of :option:`kitty --version`.
|
||||
Les versions nightly affichent la date et le hash du commit à partir duquel
|
||||
elles ont été compilées dans la sortie de :option:`kitty --version`.
|
||||
|
||||
If you want to install it in parallel to the released kitty specify a
|
||||
different install locations with ``dest``:
|
||||
Si vous voulez l'installer en parallèle de la version publiée de kitty,
|
||||
indiquez un autre emplacement d'installation avec ``dest`` :
|
||||
|
||||
.. code-block:: sh
|
||||
|
||||
_kitty_install_cmd \
|
||||
installer=nightly dest=/some/other/location
|
||||
|
||||
* You can specify a specific version to install, with:
|
||||
* Vous pouvez indiquer une version précise à installer avec :
|
||||
|
||||
.. code-block:: sh
|
||||
|
||||
_kitty_install_cmd \
|
||||
installer=version-0.35.2
|
||||
|
||||
* You can tell the installer not to launch |kitty| after installing it with
|
||||
``launch=n``:
|
||||
* Vous pouvez demander à l'installateur de ne pas lancer |kitty| après
|
||||
l'installation avec ``launch=n`` :
|
||||
|
||||
.. code-block:: sh
|
||||
|
||||
_kitty_install_cmd \
|
||||
launch=n
|
||||
|
||||
* You can use a previously downloaded dmg/tarball, with ``installer``:
|
||||
* Vous pouvez utiliser un dmg/tarball déjà téléchargé, avec ``installer`` :
|
||||
|
||||
.. code-block:: sh
|
||||
|
||||
@@ -127,14 +135,15 @@ Customizing the installation
|
||||
installer=/path/to/dmg or tarball
|
||||
|
||||
|
||||
Uninstalling
|
||||
Désinstallation
|
||||
----------------
|
||||
|
||||
All the installer does is copy the kitty files into the install directory. To
|
||||
uninstall, simply delete that directory.
|
||||
Tout ce que fait l'installateur, c'est copier les fichiers de kitty dans le
|
||||
dossier d'installation. Pour désinstaller, il suffit de supprimer ce dossier.
|
||||
|
||||
|
||||
Building from source
|
||||
------------------------
|
||||
Compiler depuis les sources
|
||||
---------------------------
|
||||
|
||||
|kitty| is easy to build from source, follow the :doc:`instructions <build>`.
|
||||
|kitty| est facile à compiler depuis les sources, suivez les :doc:`instructions
|
||||
<build>`.
|
||||
+122
-108
@@ -1,86 +1,94 @@
|
||||
Build from source
|
||||
==================
|
||||
Compiler depuis les sources
|
||||
===========================
|
||||
|
||||
.. image:: https://github.com/kovidgoyal/kitty/workflows/CI/badge.svg
|
||||
:alt: Build status
|
||||
:alt: État de la compilation
|
||||
:target: https://github.com/kovidgoyal/kitty/actions?query=workflow%3ACI
|
||||
|
||||
.. note::
|
||||
If you just want to test the latest changes to kitty, you don't need to build
|
||||
from source. Instead install the :ref:`latest nightly build <nightly>`.
|
||||
Si vous voulez simplement tester les dernières modifications de kitty, vous
|
||||
n'avez pas besoin de compiler depuis les sources. Installez plutôt la
|
||||
:ref:`dernière version nightly <nightly>`.
|
||||
|
||||
.. highlight:: sh
|
||||
|
||||
|kitty| is designed to run from source, for easy hack-ability. All you need to
|
||||
get started is a C compiler and the `go compiler
|
||||
<https://go.dev/doc/install>`__ (on Linux, the :ref:`X11 development libraries <x11-dev-libs>` as well).
|
||||
After installing those, run the following commands::
|
||||
|kitty| est conçu pour s'exécuter depuis les sources, pour faciliter le
|
||||
bricolage. Tout ce dont vous avez besoin pour démarrer est un compilateur C et
|
||||
le `compilateur go <https://go.dev/doc/install>`__ (sous Linux, également les
|
||||
:ref:`bibliothèques de développement X11 <x11-dev-libs>`). Après les avoir
|
||||
installés, lancez les commandes suivantes ::
|
||||
|
||||
git clone https://github.com/kovidgoyal/kitty.git && cd kitty
|
||||
./dev.sh build
|
||||
|
||||
That's it, kitty will be built from source, magically. You can run it as
|
||||
:file:`kitty/launcher/kitty`.
|
||||
C'est tout, kitty sera compilé depuis les sources, comme par magie. Vous pouvez
|
||||
le lancer avec :file:`kitty/launcher/kitty`.
|
||||
|
||||
This works, because the :code:`./dev.sh build` command downloads all the major
|
||||
dependencies of kitty as pre-built binaries for your platform and builds kitty
|
||||
to use these rather than system libraries. The few required system libraries
|
||||
are X11 (if you use X server) and DBUS on Linux.
|
||||
Cela fonctionne parce que la commande :code:`./dev.sh build` télécharge toutes
|
||||
les dépendances majeures de kitty sous forme de binaires précompilés pour votre
|
||||
plateforme et compile kitty pour les utiliser à la place des bibliothèques
|
||||
système. Les rares bibliothèques système requises sont X11 (si vous utilisez un
|
||||
serveur X) et DBUS sous Linux.
|
||||
|
||||
If you make changes to kitty code, simply re-run :code:`./dev.sh build`
|
||||
to build kitty with your changes.
|
||||
Si vous modifiez le code de kitty, relancez simplement
|
||||
:code:`./dev.sh build` pour compiler kitty avec vos modifications.
|
||||
|
||||
.. note::
|
||||
If you plan to run kitty from source long-term, there are a couple of
|
||||
caveats to be aware of. You should occasionally run ``./dev.sh deps``
|
||||
to have the dependencies re-downloaded as they are updated periodically.
|
||||
Also, the built kitty executable assumes it will find source in whatever
|
||||
directory you first ran :code:`./dev.sh build` in. If you move/rename the
|
||||
directory, run :code:`make clean && ./dev.sh build`. You should also create
|
||||
symlinks to the :file:`kitty` and :file:`kitten` binaries from somewhere
|
||||
in your PATH so that they can be conveniently launched.
|
||||
Si vous comptez exécuter kitty depuis les sources sur le long terme,
|
||||
quelques écueils sont à connaître. Vous devriez lancer de temps en temps
|
||||
``./dev.sh deps`` pour faire retélécharger les dépendances, car elles sont
|
||||
mises à jour périodiquement. De plus, l'exécutable kitty compilé suppose
|
||||
qu'il trouvera les sources dans le dossier où vous avez lancé
|
||||
:code:`./dev.sh build` la première fois. Si vous déplacez ou renommez le
|
||||
dossier, lancez :code:`make clean && ./dev.sh build`. Vous devriez aussi
|
||||
créer des liens symboliques vers les binaires :file:`kitty` et
|
||||
:file:`kitten` depuis un dossier de votre PATH, afin de pouvoir les lancer
|
||||
facilement.
|
||||
|
||||
.. note::
|
||||
On macOS, you can use :file:`kitty/launcher/kitty.app` to run kitty as well,
|
||||
but note that this is an unsigned kitty.app so some functionality such as
|
||||
notifications will not work as Apple disallows this. If you need this
|
||||
functionality, you can try signing the built :file:`kitty.app` with a self
|
||||
signed certificate, see for example, `here
|
||||
Sous macOS, vous pouvez aussi utiliser :file:`kitty/launcher/kitty.app`
|
||||
pour lancer kitty, mais notez que ce kitty.app n'est pas signé, donc
|
||||
certaines fonctionnalités comme les notifications ne fonctionneront pas
|
||||
car Apple l'interdit. Si vous avez besoin de cette fonctionnalité, vous
|
||||
pouvez essayer de signer le :file:`kitty.app` compilé avec un certificat
|
||||
auto-signé, voir par exemple `ici
|
||||
<https://stackoverflow.com/questions/27474751/how-can-i-codesign-an-app-without-being-in-the-mac-developer-program/27474942>`__.
|
||||
|
||||
Building in debug mode
|
||||
Compiler en mode debug
|
||||
^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
The following will build with debug symbols::
|
||||
Ce qui suit compile avec les symboles de debug ::
|
||||
|
||||
./dev.sh build --debug
|
||||
|
||||
To build with sanitizers and debug symbols::
|
||||
Pour compiler avec les sanitizers et les symboles de debug ::
|
||||
|
||||
./dev.sh build --debug --sanitize
|
||||
|
||||
For more help on the various options supported by the build script::
|
||||
Pour plus d'aide sur les différentes options prises en charge par le script de
|
||||
compilation ::
|
||||
|
||||
./dev.sh build -h
|
||||
|
||||
|
||||
Building the documentation
|
||||
Compiler la documentation
|
||||
-------------------------------------
|
||||
|
||||
To have the kitty documentation available locally, run::
|
||||
Pour avoir la documentation de kitty disponible en local, lancez ::
|
||||
|
||||
./dev.sh deps -for-docs && ./dev.sh docs
|
||||
|
||||
To develop the docs, with live reloading, use::
|
||||
Pour développer la documentation, avec rechargement automatique, utilisez ::
|
||||
|
||||
./dev.sh deps -for-docs && ./dev.sh docs -live-reload
|
||||
|
||||
Dependencies
|
||||
Dépendances
|
||||
----------------
|
||||
|
||||
These dependencies are needed when building against system libraries only.
|
||||
Ces dépendances sont nécessaires uniquement lorsque vous compilez contre les
|
||||
bibliothèques système.
|
||||
|
||||
Run-time dependencies:
|
||||
Dépendances d'exécution :
|
||||
|
||||
* ``python`` >= 3.12
|
||||
* ``harfbuzz`` >= 2.2.0
|
||||
@@ -89,29 +97,29 @@ Run-time dependencies:
|
||||
* ``liblcms2``
|
||||
* ``libxxhash``
|
||||
* ``openssl``
|
||||
* ``shader-slang`` (needed only if you use custom shaders)
|
||||
* ``pixman`` (not needed on macOS)
|
||||
* ``cairo`` (not needed on macOS)
|
||||
* ``freetype`` (not needed on macOS)
|
||||
* ``fontconfig`` (not needed on macOS)
|
||||
* ``libcanberra`` (not needed on macOS)
|
||||
* ``libsystemd`` (optional, not needed on non systemd systems)
|
||||
* ``ImageMagick`` (optional, needed to display uncommon image formats in the terminal)
|
||||
* ``X11 libraries`` (optional, needed if you use X11 on Linux)
|
||||
* ``Wayland libraries`` (optional, needed if you use Wayland on Linux)
|
||||
* ``shader-slang`` (nécessaire uniquement si vous utilisez des shaders personnalisés)
|
||||
* ``pixman`` (non nécessaire sous macOS)
|
||||
* ``cairo`` (non nécessaire sous macOS)
|
||||
* ``freetype`` (non nécessaire sous macOS)
|
||||
* ``fontconfig`` (non nécessaire sous macOS)
|
||||
* ``libcanberra`` (non nécessaire sous macOS)
|
||||
* ``libsystemd`` (facultatif, non nécessaire sur les systèmes sans systemd)
|
||||
* ``ImageMagick`` (facultatif, nécessaire pour afficher les formats d'image peu courants dans le terminal)
|
||||
* ``X11 libraries`` (facultatif, nécessaire si vous utilisez X11 sous Linux)
|
||||
* ``Wayland libraries`` (facultatif, nécessaire si vous utilisez Wayland sous Linux)
|
||||
|
||||
|
||||
Build-time dependencies:
|
||||
Dépendances de compilation :
|
||||
|
||||
* ``gcc`` or ``clang``
|
||||
* ``gcc`` ou ``clang``
|
||||
* ``simde``
|
||||
* ``shader-slang``
|
||||
* ``go`` >= _build_go_version (see :file:`go.mod` for go packages used during building)
|
||||
* ``go`` >= _build_go_version (voir :file:`go.mod` pour les paquets go utilisés lors de la compilation)
|
||||
* ``pkg-config``
|
||||
* Symbols NERD Font Mono either installed system-wide or placed in :file:`fonts/SymbolsNerdFontMono-Regular.ttf`
|
||||
* For building on Linux in addition to the above dependencies you might also
|
||||
need to install the following packages, if they are not already installed by
|
||||
your distro:
|
||||
* Symbols NERD Font Mono, installée à l'échelle du système ou placée dans :file:`fonts/SymbolsNerdFontMono-Regular.ttf`
|
||||
* Pour compiler sous Linux, en plus des dépendances ci-dessus, vous devrez
|
||||
peut-être installer les paquets suivants s'ils ne sont pas déjà installés
|
||||
par votre distribution :
|
||||
|
||||
- ``liblcms2-dev``
|
||||
- ``libfontconfig-dev``
|
||||
@@ -123,7 +131,7 @@ Build-time dependencies:
|
||||
|
||||
.. _x11-dev-libs:
|
||||
|
||||
Also, the X11 development libraries:
|
||||
Ainsi que les bibliothèques de développement X11 :
|
||||
|
||||
- ``libdbus-1-dev``
|
||||
- ``libxcursor-dev``
|
||||
@@ -137,84 +145,90 @@ Build-time dependencies:
|
||||
|
||||
|
||||
|
||||
Build and run from source with Nix
|
||||
-------------------------------------------
|
||||
Compiler et exécuter depuis les sources avec Nix
|
||||
------------------------------------------------
|
||||
|
||||
On NixOS or any other Linux or macOS system with the Nix package manager
|
||||
installed, execute `nix-shell
|
||||
<https://nixos.org/guides/nix-pills/developing-with-nix-shell.html>`__ to create
|
||||
the correct environment to build kitty or use ``nix-shell --pure`` instead to
|
||||
eliminate most of the influence of the outside system, e.g. globally installed
|
||||
packages. ``nix-shell`` will automatically fetch all required dependencies and
|
||||
make them available in the newly spawned shell.
|
||||
Sous NixOS ou tout autre système Linux ou macOS disposant du gestionnaire de
|
||||
paquets Nix, exécutez `nix-shell
|
||||
<https://nixos.org/guides/nix-pills/developing-with-nix-shell.html>`__ pour
|
||||
créer l'environnement correct afin de compiler kitty, ou utilisez plutôt
|
||||
``nix-shell --pure`` pour éliminer la plupart de l'influence du système
|
||||
extérieur, par exemple les paquets installés globalement. ``nix-shell``
|
||||
récupérera automatiquement toutes les dépendances requises et les rendra
|
||||
disponibles dans le shell nouvellement lancé.
|
||||
|
||||
Then proceed with ``make`` or ``make app`` according to the platform specific
|
||||
instructions above.
|
||||
Puis poursuivez avec ``make`` ou ``make app`` selon les instructions propres à
|
||||
votre plateforme ci-dessus.
|
||||
|
||||
.. _packagers:
|
||||
|
||||
Notes for Linux/macOS packagers
|
||||
----------------------------------
|
||||
Notes pour les empaqueteurs Linux/macOS
|
||||
---------------------------------------
|
||||
|
||||
The released |kitty| source code is available as a `tarball`_ from
|
||||
`the GitHub releases page <https://github.com/kovidgoyal/kitty/releases>`__.
|
||||
Le code source publié de |kitty| est disponible sous forme de `tarball`_ depuis
|
||||
`la page des versions GitHub
|
||||
<https://github.com/kovidgoyal/kitty/releases>`__.
|
||||
|
||||
While |kitty| does use Python, it is not a traditional Python package, so please
|
||||
do not install it in site-packages.
|
||||
Instead run::
|
||||
Bien que |kitty| utilise Python, ce n'est pas un paquet Python traditionnel,
|
||||
donc ne l'installez pas dans site-packages. Lancez plutôt ::
|
||||
|
||||
make linux-package
|
||||
|
||||
This will install |kitty| into the directory :file:`linux-package`. You can run
|
||||
|kitty| with :file:`linux-package/bin/kitty`. All the files needed to run kitty
|
||||
will be in :file:`linux-package/lib/kitty`. The terminfo file will be installed
|
||||
into :file:`linux-package/share/terminfo`. Simply copy these files into
|
||||
:file:`/usr` to install |kitty|. In other words, :file:`linux-package` is the
|
||||
staging area into which |kitty| is installed. You can choose a different staging
|
||||
area, by passing the ``--prefix`` argument to :file:`setup.py`.
|
||||
Cela installera |kitty| dans le dossier :file:`linux-package`. Vous pouvez
|
||||
lancer |kitty| avec :file:`linux-package/bin/kitty`. Tous les fichiers
|
||||
nécessaires à l'exécution de kitty se trouveront dans
|
||||
:file:`linux-package/lib/kitty`. Le fichier terminfo sera installé dans
|
||||
:file:`linux-package/share/terminfo`. Il suffit de copier ces fichiers dans
|
||||
:file:`/usr` pour installer |kitty|. Autrement dit, :file:`linux-package` est
|
||||
la zone de préparation dans laquelle |kitty| est installé. Vous pouvez choisir
|
||||
une autre zone de préparation en passant l'argument ``--prefix`` à
|
||||
:file:`setup.py`.
|
||||
|
||||
You should probably split |kitty| into three packages:
|
||||
Vous devriez probablement découper |kitty| en trois paquets :
|
||||
|
||||
:code:`kitty-terminfo`
|
||||
Installs the terminfo file
|
||||
Installe le fichier terminfo
|
||||
|
||||
:code:`kitty-shell-integration`
|
||||
Installs the shell integration scripts (the contents of the
|
||||
shell-integration directory in the kitty source code), probably to
|
||||
Installe les scripts d'intégration du shell (le contenu du dossier
|
||||
shell-integration du code source de kitty), probablement dans
|
||||
:file:`/usr/share/kitty/shell-integration`
|
||||
|
||||
:code:`kitty`
|
||||
Installs the main program
|
||||
Installe le programme principal
|
||||
|
||||
This allows users to install the terminfo and shell integration files on
|
||||
servers into which they ssh, without needing to install all of |kitty|. The
|
||||
shell integration files **must** still be present in
|
||||
:file:`lib/kitty/shell-integration` when installing the kitty main package as
|
||||
the kitty program expects to find them there.
|
||||
Cela permet aux utilisateurs d'installer les fichiers terminfo et
|
||||
d'intégration du shell sur les serveurs auxquels ils se connectent en SSH, sans
|
||||
avoir à installer tout |kitty|. Les fichiers d'intégration du shell **doivent**
|
||||
tout de même être présents dans :file:`lib/kitty/shell-integration` lors de
|
||||
l'installation du paquet principal kitty, car le programme kitty s'attend à les
|
||||
y trouver.
|
||||
|
||||
.. note::
|
||||
You need a couple of extra dependencies to build linux-package. :file:`tic`
|
||||
to compile terminfo files, usually found in the development package of
|
||||
:file:`ncurses`. Also, if you are building from a git checkout instead of the
|
||||
released source code tarball, you will need to install the dependencies from
|
||||
:file:`docs/requirements.txt` to build the kitty documentation. They can be
|
||||
installed most easily with ``python -m pip install -r docs/requirements.txt``.
|
||||
Vous avez besoin de quelques dépendances supplémentaires pour construire
|
||||
linux-package. :file:`tic` pour compiler les fichiers terminfo, généralement
|
||||
fourni dans le paquet de développement de :file:`ncurses`. De plus, si vous
|
||||
compilez depuis un dépôt git plutôt que depuis l'archive des sources
|
||||
publiées, vous devrez installer les dépendances de
|
||||
:file:`docs/requirements.txt` pour compiler la documentation de kitty. Elles
|
||||
s'installent le plus facilement avec ``python -m pip install -r docs/requirements.txt``.
|
||||
|
||||
This applies to creating packages for |kitty| for macOS package managers such as
|
||||
Homebrew or MacPorts as well.
|
||||
Cela vaut aussi pour la création de paquets de |kitty| pour les gestionnaires
|
||||
de paquets macOS tels que Homebrew ou MacPorts.
|
||||
|
||||
Cross compilation
|
||||
Compilation croisée
|
||||
-------------------
|
||||
|
||||
While cross compilation is neither officially supported, nor recommended, as it
|
||||
means the test suite cannot be run for the cross compiled build, there is some
|
||||
support for cross compilation. Basically, run::
|
||||
La compilation croisée n'est ni officiellement prise en charge ni recommandée,
|
||||
car cela signifie que la suite de tests ne peut pas être exécutée sur la
|
||||
compilation croisée, mais elle est partiellement prise en charge. En résumé,
|
||||
lancez ::
|
||||
|
||||
make prepare-for-cross-compile
|
||||
|
||||
Then setup the cross compile environment (CC, CFLAGS, PATH, etc.) and run::
|
||||
Configurez ensuite l'environnement de compilation croisée (CC, CFLAGS, PATH,
|
||||
etc.) et lancez ::
|
||||
|
||||
make cross-compile
|
||||
|
||||
This will create the cross compiled build in the :file:`linux-package`
|
||||
directory.
|
||||
Cela créera la compilation croisée dans le dossier :file:`linux-package`.
|
||||
@@ -219,9 +219,193 @@ you use a decent Wayland compositor.
|
||||
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]
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
- :opt:`notify_on_cmd_finish` is now enabled by default with the value
|
||||
:code:`unfocused`: commands running longer than 5 seconds notify when the
|
||||
window loses focus, without any configuration. Use :code:`never` to turn it
|
||||
off.
|
||||
|
||||
- The :opt:`notify_on_cmd_finish` notification now reports how long the command
|
||||
ran, next to the command line and the exit status it already showed. A shell
|
||||
that ends a command without reporting a status (:code:`OSC 133;D` with no
|
||||
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
|
||||
<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
|
||||
:kbd:`Ctrl+Shift+E` to :code:`open_url_with_hints` in :file:`kitty.conf` to
|
||||
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
|
||||
:doc:`file manager <kittens/file-manager>` and the
|
||||
:doc:`command palette <kittens/command-palette>` by default. A new
|
||||
:doc:`accessibility guide </accessibility>` documents keyboard navigation and
|
||||
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
|
||||
:code:`kitten file-manager`, that browses directories in a side panel and
|
||||
changes the working directory of the shell that launched it without leaving
|
||||
the shell. It opens files in the configured editor, optionally through
|
||||
:code:`sudo`, and can open them in its own window with :code:`--open-here` so
|
||||
that it stays usable in a dock. It also copies paths and creates, renames and
|
||||
deletes entries after a confirmation
|
||||
|
||||
- The :doc:`file manager <kittens/file-manager>` can now filter its listing
|
||||
with a fuzzy query (:kbd:`/`), list and run its actions from an in-panel
|
||||
palette (:kbd:`:`), and open the selected file in a new tab (:kbd:`O`) or a
|
||||
new OS window (:kbd:`T`). Entries can also be sorted by size with
|
||||
:code:`sort_by size`.
|
||||
|
||||
- The :doc:`file manager <kittens/file-manager>` documentation now covers its
|
||||
shell integration and its limits (no preview, no volume handling, no
|
||||
recursive deletion, no privileged files), and is listed in the kittens
|
||||
overview next to the other built-in kittens.
|
||||
|
||||
- :doc:`choose-files <kittens/choose-files>`: Fix concurrent custom preview
|
||||
commands occasionally receiving the path of a different file.
|
||||
|
||||
|
||||
@@ -264,3 +264,37 @@ to access the clipboard.
|
||||
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
|
||||
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.
|
||||
+12
-6
@@ -20,7 +20,7 @@ from docutils import nodes
|
||||
from docutils.parsers.rst.roles import normalize_options
|
||||
from pygments.lexer import RegexLexer
|
||||
from pygments.lexer import bygroups as untyped_bygroups
|
||||
from pygments.token import Comment, Error, Keyword, Literal, Name, Number, String, Whitespace
|
||||
from pygments.token import Comment, Error, Keyword, Literal, Name, Number, Punctuation, String, Whitespace
|
||||
from sphinx import addnodes, version_info
|
||||
from sphinx.util.logging import getLogger
|
||||
|
||||
@@ -220,15 +220,19 @@ def commit_role(
|
||||
name: str, rawtext: str, text: str, lineno: int, inliner: Any, options: Any = {}, content: Any = []
|
||||
) -> Tuple[List[nodes.reference], List[nodes.problematic]]:
|
||||
"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:
|
||||
commit_id = subprocess.check_output(f'git rev-list --max-count=1 {text}'.split()).decode('utf-8').strip()
|
||||
commit_id = subprocess.check_output(f'git rev-list --max-count=1 {text}'.split(), stderr=subprocess.DEVNULL).decode('utf-8').strip()
|
||||
except Exception:
|
||||
msg = inliner.reporter.error(f'git commit id "{text}" not recognized.', line=lineno)
|
||||
prb = inliner.problematic(rawtext, rawtext, msg)
|
||||
return [prb], [msg]
|
||||
commit_id = text
|
||||
url = f'https://github.com/kovidgoyal/kitty/commit/{commit_id}'
|
||||
options = normalize_options(options)
|
||||
short_id = subprocess.check_output(f'git rev-list --max-count=1 --abbrev-commit {commit_id}'.split()).decode('utf-8').strip()
|
||||
try:
|
||||
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)
|
||||
return [node], []
|
||||
|
||||
@@ -507,6 +511,8 @@ class ConfLexer(RegexLexer):
|
||||
tokens = {
|
||||
'root': [
|
||||
(r'#.*?$', Comment.Single),
|
||||
# Closing brace of a profile block, see :ref:`config-profiles`.
|
||||
(r'\}', Punctuation),
|
||||
(r'\s+$', Whitespace),
|
||||
(r'\s+', Whitespace),
|
||||
(r'(include)(\s+)(.+?)$', bygroups(Comment.Preproc, Whitespace, Name.Namespace)),
|
||||
|
||||
+96
-53
@@ -6,93 +6,136 @@ kitty.conf
|
||||
|
||||
.. only:: man
|
||||
|
||||
Overview
|
||||
Vue d'ensemble
|
||||
--------------
|
||||
|
||||
|
||||
|kitty| is highly customizable, everything from keyboard shortcuts, to rendering
|
||||
frames-per-second. See below for an overview of all customization possibilities.
|
||||
|kitty| est hautement personnalisable, des raccourcis clavier jusqu'au nombre
|
||||
d'images par seconde. Voir ci-dessous une vue d'ensemble de toutes les
|
||||
possibilités de personnalisation.
|
||||
|
||||
You can open the config file within |kitty| by pressing :sc:`edit_config_file`
|
||||
(:kbd:`⌘+,` on macOS). A :file:`kitty.conf` with commented default
|
||||
configurations and descriptions will be created if the file does not exist.
|
||||
The configuration is automatically reloaded when modified, controlled by
|
||||
:opt:`auto_reload_config`. You can manually reload the config by pressing
|
||||
:sc:`reload_config_file` (:kbd:`⌃+⌘+,` on macOS) or sending |kitty| the
|
||||
``SIGUSR1`` signal with ``kill -SIGUSR1 $KITTY_PID``. You can also display the
|
||||
current configuration by pressing :sc:`debug_config` (:kbd:`⌥+⌘+,` on macOS).
|
||||
Vous pouvez ouvrir le fichier de configuration dans |kitty| en appuyant sur
|
||||
:sc:`edit_config_file` (:kbd:`⌘+,` sous macOS). Un :file:`kitty.conf` contenant
|
||||
les configurations par défaut commentées et leurs descriptions sera créé si le
|
||||
fichier n'existe pas. La configuration est rechargée automatiquement lorsqu'elle
|
||||
est modifiée, ce qui est contrôlé par :opt:`auto_reload_config`. Vous pouvez
|
||||
recharger manuellement la configuration en appuyant sur
|
||||
:sc:`reload_config_file` (:kbd:`⌃+⌘+,` sous macOS) ou en envoyant le signal
|
||||
``SIGUSR1`` à |kitty| avec ``kill -SIGUSR1 $KITTY_PID``. Vous pouvez aussi
|
||||
afficher la configuration courante en appuyant sur :sc:`debug_config`
|
||||
(:kbd:`⌥+⌘+,` sous macOS).
|
||||
|
||||
.. _confloc:
|
||||
|
||||
|kitty| looks for a config file in the OS config directories (usually
|
||||
:file:`~/.config/kitty/kitty.conf`) but you can pass a specific path via the
|
||||
:option:`kitty --config` option or use the :envvar:`KITTY_CONFIG_DIRECTORY`
|
||||
environment variable. See :option:`kitty --config` for full details.
|
||||
|kitty| cherche un fichier de configuration dans les dossiers de configuration
|
||||
du système (généralement :file:`~/.config/kitty/kitty.conf`), mais vous pouvez
|
||||
indiquer un chemin particulier avec l'option :option:`kitty --config` ou la
|
||||
variable d'environnement :envvar:`KITTY_CONFIG_DIRECTORY`. Voir
|
||||
:option:`kitty --config` pour tous les détails.
|
||||
|
||||
**Comments** can be added to the config file as lines whose first non-whitespace
|
||||
character is ``#``. Trailing comments after configuration values are not
|
||||
generally supported.
|
||||
**Les commentaires** peuvent être ajoutés au fichier de configuration sous forme
|
||||
de lignes dont le premier caractère non blanc est ``#``. Les commentaires en fin
|
||||
de ligne, après une valeur de configuration, ne sont généralement pas pris en
|
||||
charge.
|
||||
|
||||
**Lines can be split** by starting the next line with the ``\`` character.
|
||||
All leading whitespace and the ``\`` character are removed.
|
||||
**Les lignes peuvent être scindées** en commençant la ligne suivante par le
|
||||
caractère ``\``. Tous les espaces de début et le caractère ``\`` sont supprimés.
|
||||
|
||||
.. _include:
|
||||
|
||||
You can **include secondary config files** via the :code:`include` directive. If
|
||||
you use a relative path for :code:`include`, it is resolved with respect to the
|
||||
location of the current config file. Note that environment variables are
|
||||
expanded, so :code:`${USER}.conf` becomes :file:`name.conf` if
|
||||
:code:`USER=name`. A special environment variable :envvar:`KITTY_OS` is available,
|
||||
to detect the operating system. It is ``linux``, ``macos`` or ``bsd``.
|
||||
Also, you can use :code:`globinclude` to include files
|
||||
matching a shell glob pattern and :code:`envinclude` to include configuration
|
||||
from environment variables. Finally, you can dynamically generate configuration
|
||||
by running a program using :code:`geninclude`. For example::
|
||||
Vous pouvez **inclure des fichiers de configuration secondaires** via la
|
||||
directive :code:`include`. Si vous utilisez un chemin relatif pour
|
||||
:code:`include`, il est résolu par rapport à l'emplacement du fichier de
|
||||
configuration courant. Notez que les variables d'environnement sont expandues,
|
||||
donc :code:`${USER}.conf` devient :file:`name.conf` si :code:`USER=name`. Une
|
||||
variable d'environnement spéciale :envvar:`KITTY_OS` est disponible pour
|
||||
détecter le système d'exploitation. Elle vaut ``linux``, ``macos`` ou ``bsd``.
|
||||
Vous pouvez également utiliser :code:`globinclude` pour inclure les fichiers
|
||||
correspondant à un motif glob du shell et :code:`envinclude` pour inclure la
|
||||
configuration depuis des variables d'environnement. Enfin, vous pouvez générer
|
||||
dynamiquement la configuration en exécutant un programme avec
|
||||
:code:`geninclude`. Par exemple ::
|
||||
|
||||
# Include other.conf
|
||||
# Inclut other.conf
|
||||
include other.conf
|
||||
# Include *.conf files from all subdirs of kitty.d inside the kitty config dir
|
||||
# Inclut les fichiers *.conf de tous les sous-dossiers de kitty.d dans le dossier de config de kitty
|
||||
globinclude kitty.d/**/*.conf
|
||||
# Include the *contents* of all env vars starting with KITTY_CONF_
|
||||
# Inclut le *contenu* de toutes les variables d'env commençant par KITTY_CONF_
|
||||
envinclude KITTY_CONF_*
|
||||
# Run the script dynamic.py placed in the same directory as this config file
|
||||
# and include its :file:`STDOUT`. Note that Python scripts are fastest
|
||||
# as they use the embedded Python interpreter, but any executable script
|
||||
# or program is supported, in any language. Remember to mark the script
|
||||
# file executable.
|
||||
# Lance le script dynamic.py placé dans le même dossier que ce fichier de configuration
|
||||
# et inclut sa :file:`STDOUT`. Notez que les scripts Python sont les plus rapides
|
||||
# car ils utilisent l'interpréteur Python embarqué, mais tout script exécutable
|
||||
# ou programme est accepté, dans n'importe quel langage. Pensez à rendre le fichier
|
||||
# de script exécutable.
|
||||
geninclude dynamic.py
|
||||
|
||||
|
||||
.. _config-profiles:
|
||||
|
||||
Profils de configuration
|
||||
------------------------
|
||||
|
||||
Vous pouvez regrouper des réglages dans des profils nommés, à l'intérieur de
|
||||
:file:`kitty.conf`, et n'en appliquer qu'un seul au démarrage. Un profil est un
|
||||
bloc de configuration ordinaire délimité par des accolades ::
|
||||
|
||||
font_size 11
|
||||
|
||||
profile work {
|
||||
font_size 9
|
||||
background_opacity 1
|
||||
}
|
||||
|
||||
Les lignes d'un bloc :code:`profile` ne sont appliquées que si ce profil est
|
||||
sélectionné. La priorité est la suivante : profil, puis configuration globale,
|
||||
puis valeurs par défaut. Un profil ne surcharge donc que les options qu'il
|
||||
contient ; les autres conservent leur valeur habituelle.
|
||||
|
||||
Sélectionnez un profil avec l'option :option:`kitty --profile` ou avec la
|
||||
variable d'environnement :envvar:`KITTY_PROFILE`, qui permet de lier un profil à
|
||||
un projet dans un script de lancement. Si le profil demandé est inconnu, ou si
|
||||
l'une de ses lignes est invalide, l'erreur est signalée mais |kitty| démarre
|
||||
quand même avec le reste de la configuration.
|
||||
|
||||
Les profils ne peuvent pas être imbriqués. Ils peuvent toutefois utiliser
|
||||
: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
|
||||
|
||||
|
||||
Sample kitty.conf
|
||||
--------------------
|
||||
Exemple de kitty.conf
|
||||
---------------------
|
||||
|
||||
.. only:: html
|
||||
|
||||
You can download a sample :file:`kitty.conf` file with all default settings
|
||||
and comments describing each setting by clicking: :download:`sample
|
||||
kitty.conf </generated/conf/kitty.conf>`.
|
||||
Vous pouvez télécharger un exemple de fichier :file:`kitty.conf` contenant
|
||||
tous les réglages par défaut et des commentaires décrivant chaque réglage en
|
||||
cliquant ici : :download:`exemple de kitty.conf </generated/conf/kitty.conf>`.
|
||||
|
||||
.. only:: man
|
||||
|
||||
You can edit a fully commented sample kitty.conf by pressing the
|
||||
:sc:`edit_config_file` shortcut in kitty. This will generate a config file
|
||||
with full documentation and all settings commented out. If you have a
|
||||
pre-existing :file:`kitty.conf`, then that will be used instead, delete it to
|
||||
see the sample file.
|
||||
Vous pouvez éditer un exemple entièrement commenté de kitty.conf en appuyant
|
||||
sur le raccourci :sc:`edit_config_file` dans kitty. Cela générera un fichier
|
||||
de configuration avec la documentation complète et tous les réglages
|
||||
commentés. Si un :file:`kitty.conf` existe déjà, c'est lui qui sera utilisé ;
|
||||
supprimez-le pour voir le fichier d'exemple.
|
||||
|
||||
A default configuration file can also be generated by running::
|
||||
Un fichier de configuration par défaut peut aussi être généré en lançant ::
|
||||
|
||||
kitty +runpy 'from kitty.config import *; print(commented_out_default_config())'
|
||||
|
||||
This will print the commented out default config file to :file:`STDOUT`.
|
||||
Cela affichera le fichier de configuration par défaut commenté sur
|
||||
:file:`STDOUT`.
|
||||
|
||||
All mappable actions
|
||||
------------------------
|
||||
Toutes les actions associables
|
||||
------------------------------
|
||||
|
||||
See the :doc:`list of all the things you can make |kitty| can do </actions>`.
|
||||
Voir la :doc:`liste de tout ce que vous pouvez faire faire à |kitty| </actions>`.
|
||||
|
||||
.. toctree::
|
||||
:hidden:
|
||||
|
||||
+180
-141
@@ -1,277 +1,316 @@
|
||||
:orphan:
|
||||
|
||||
Glossary
|
||||
Glossaire
|
||||
=========
|
||||
|
||||
.. glossary::
|
||||
|
||||
os_window
|
||||
kitty has two kinds of windows. Operating System windows, referred to as :term:`OS
|
||||
Window <os_window>`, and *kitty windows*. An OS Window consists of one or more kitty
|
||||
:term:`tabs <tab>`. Each tab in turn consists of one or more *kitty
|
||||
windows* organized in a :term:`layout`.
|
||||
kitty possède deux types de fenêtres. Les fenêtres du système
|
||||
d'exploitation, appelées :term:`fenêtres OS <os_window>`, et les *fenêtres
|
||||
kitty*. Une fenêtre OS contient un ou plusieurs :term:`onglets <tab>`
|
||||
kitty. Chaque onglet contient à son tour une ou plusieurs *fenêtres kitty*
|
||||
organisées selon une :term:`disposition <layout>`.
|
||||
|
||||
tab
|
||||
A *tab* refers to a group of :term:`kitty windows <window>`, organized in
|
||||
a :term:`layout`. Every :term:`OS Window <os_window>` contains one or more tabs.
|
||||
Un *onglet* désigne un groupe de :term:`fenêtres kitty <window>`, organisé
|
||||
selon une :term:`disposition <layout>`. Chaque :term:`fenêtre OS
|
||||
<os_window>` contient un ou plusieurs onglets.
|
||||
|
||||
layout
|
||||
A *layout* is a system of organizing :term:`kitty windows <window>` in
|
||||
groups inside a tab. The layout automatically maintains the size and
|
||||
position of the windows, think of a layout as a tiling window manager for
|
||||
the terminal. See :doc:`layouts` for details.
|
||||
Une *disposition* est un système d'organisation des :term:`fenêtres kitty
|
||||
<window>` en groupes à l'intérieur d'un onglet. La disposition maintient
|
||||
automatiquement la taille et la position des fenêtres ; voyez-la comme un
|
||||
gestionnaire de fenêtres en mosaïque pour le terminal. Voir
|
||||
:doc:`layouts` pour les détails.
|
||||
|
||||
window
|
||||
kitty has two kinds of windows. Operating System windows, referred to as :term:`OS
|
||||
Window <os_window>`, and *kitty windows*. An OS Window consists of one or more kitty
|
||||
:term:`tabs <tab>`. Each tab in turn consists of one or more *kitty
|
||||
windows* organized in a :term:`layout`.
|
||||
kitty possède deux types de fenêtres. Les fenêtres du système
|
||||
d'exploitation, appelées :term:`fenêtres OS <os_window>`, et les *fenêtres
|
||||
kitty*. Une fenêtre OS contient un ou plusieurs :term:`onglets <tab>`
|
||||
kitty. Chaque onglet contient à son tour une ou plusieurs *fenêtres kitty*
|
||||
organisées selon une :term:`disposition <layout>`.
|
||||
|
||||
overlay
|
||||
An *overlay window* is a :term:`kitty window <window>` that is placed on
|
||||
top of an existing kitty window, entirely covering it. Overlays are used
|
||||
throughout kitty, for example, to display the :ref:`the scrollback buffer <scrollback>`,
|
||||
to display :doc:`hints </kittens/hints>`, for :doc:`unicode input
|
||||
</kittens/unicode_input>` etc. Normal overlays are meant for short
|
||||
duration popups and so are not considered the :italic:`active window`
|
||||
when determining the current working directory or getting input text for
|
||||
kittens, launch commands, etc. To create an overlay considered as a
|
||||
:italic:`main window` use the :code:`overlay-main` argument to
|
||||
:doc:`launch`.
|
||||
Une *fenêtre en surcouche* est une :term:`fenêtre kitty <window>` placée
|
||||
au-dessus d'une fenêtre kitty existante et la recouvrant entièrement. Les
|
||||
surcouches sont utilisées partout dans kitty, par exemple pour afficher
|
||||
:ref:`le tampon d'historique <scrollback>`, pour afficher :doc:`les
|
||||
indices </kittens/hints>`, pour :doc:`la saisie Unicode
|
||||
</kittens/unicode_input>`, etc. Les surcouches normales sont destinées à
|
||||
des fenêtres contextuelles de courte durée et ne sont donc pas
|
||||
considérées comme la :italic:`fenêtre active` lors de la détermination du
|
||||
répertoire de travail courant ou de la récupération du texte saisi pour
|
||||
les kittens, les commandes launch, etc. Pour créer une surcouche
|
||||
considérée comme une :italic:`fenêtre principale`, utilisez l'argument
|
||||
:code:`overlay-main` de :doc:`launch`.
|
||||
|
||||
hyperlinks
|
||||
Terminals can have hyperlinks, just like the internet. In kitty you can
|
||||
:doc:`control exactly what happens <open_actions>` when clicking on a
|
||||
hyperlink, based on the type of link and its URL. See also `Hyperlinks in terminal
|
||||
emulators <https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda>`__.
|
||||
Les terminaux peuvent contenir des liens hypertextes, comme l'internet.
|
||||
Dans kitty, vous pouvez :doc:`contrôler exactement ce qui se passe
|
||||
<open_actions>` lors d'un clic sur un lien, selon le type de lien et son
|
||||
URL. Voir aussi `Hyperlinks in terminal emulators
|
||||
<https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda>`__.
|
||||
|
||||
kittens
|
||||
Small, independent statically compiled command line programs that are designed to run
|
||||
inside kitty windows and provide it with lots of powerful and flexible
|
||||
features such as viewing images, connecting conveniently to remote
|
||||
computers, transferring files, inputting unicode characters, etc.
|
||||
They can also be written by users in Python and used to customize and
|
||||
extend kitty functionality, see :doc:`kittens_intro` for details.
|
||||
The vast majority of kittens that ship with kitty are written in Go,
|
||||
with a small Python shim to handle the in-process part of the
|
||||
interaction.
|
||||
Petits programmes en ligne de commande, indépendants et compilés
|
||||
statiquement, conçus pour s'exécuter dans les fenêtres kitty et lui
|
||||
apporter de nombreuses fonctionnalités puissantes et souples, comme
|
||||
l'affichage d'images, la connexion pratique à des ordinateurs distants,
|
||||
le transfert de fichiers, la saisie de caractères Unicode, etc.
|
||||
Ils peuvent aussi être écrits par les utilisateurs en Python et servir à
|
||||
personnaliser et étendre les fonctionnalités de kitty, voir
|
||||
:doc:`kittens_intro` pour les détails. La grande majorité des kittens
|
||||
fournis avec kitty sont écrits en Go, avec une petite surcouche Python
|
||||
pour gérer la partie de l'interaction qui se fait dans le processus.
|
||||
|
||||
easing function
|
||||
A function that controls how an animation progresses over time. kitty
|
||||
support the `CSS syntax for easing functions
|
||||
<https://developer.mozilla.org/en-US/docs/Web/CSS/easing-function>`__.
|
||||
Commonly used easing functions are :code:`linear` for a constant rate
|
||||
animation and :code:`ease-in-out` for an animation that starts slow,
|
||||
becomes fast in the middle and ends slowly. These are used to control
|
||||
various animations in kitty, such as :opt:`cursor_blink_interval` and
|
||||
Une fonction qui contrôle la progression d'une animation dans le temps.
|
||||
kitty prend en charge la `syntaxe CSS des fonctions d'interpolation
|
||||
<https://developer.mozilla.org/fr/docs/Web/CSS/easing-function>`__. Les
|
||||
fonctions les plus courantes sont :code:`linear` pour une animation à
|
||||
vitesse constante et :code:`ease-in-out` pour une animation qui démarre
|
||||
lentement, s'accélère au milieu et se termine lentement. Elles contrôlent
|
||||
diverses animations de kitty, comme :opt:`cursor_blink_interval` et
|
||||
:opt:`visual_bell_duration`.
|
||||
|
||||
SIMD
|
||||
A programming technique that refers to having a single CPU instruction
|
||||
process multiple units of data, also called vector programming. Leads to
|
||||
large speedups for various data processing tasks.
|
||||
Une technique de programmation consistant à faire traiter plusieurs
|
||||
unités de données par une seule instruction du processeur, aussi appelée
|
||||
programmation vectorielle. Elle apporte d'importants gains de vitesse
|
||||
pour diverses tâches de traitement de données.
|
||||
|
||||
.. _env_vars:
|
||||
|
||||
Environment variables
|
||||
------------------------
|
||||
Variables d'environnement
|
||||
-------------------------
|
||||
|
||||
Variables that influence kitty behavior
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
Variables qui influencent le comportement de kitty
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. envvar:: KITTY_CONFIG_DIRECTORY
|
||||
|
||||
Controls where kitty looks for :file:`kitty.conf` and other configuration
|
||||
files. Defaults to :file:`~/.config/kitty`. For full details of the config
|
||||
directory lookup mechanism see, :option:`kitty --config`.
|
||||
Contrôle l'endroit où kitty cherche :file:`kitty.conf` et les autres
|
||||
fichiers de configuration. Par défaut :file:`~/.config/kitty`. Pour tous les
|
||||
détails du mécanisme de recherche du dossier de configuration, voir
|
||||
:option:`kitty --config`.
|
||||
|
||||
.. envvar:: KITTY_CACHE_DIRECTORY
|
||||
|
||||
Controls where kitty stores cache files. Defaults to :file:`~/.cache/kitty`
|
||||
or :file:`~/Library/Caches/kitty` on macOS.
|
||||
Contrôle l'endroit où kitty stocke ses fichiers de cache. Par défaut
|
||||
:file:`~/.cache/kitty` ou :file:`~/Library/Caches/kitty` sous macOS.
|
||||
|
||||
.. envvar:: KITTY_RUNTIME_DIRECTORY
|
||||
|
||||
Controls where kitty stores runtime files like sockets. On macOS, the
|
||||
default is the native per-user cache directory returned by
|
||||
:code:`getconf DARWIN_USER_CACHE_DIR`. On other platforms, kitty uses
|
||||
:code:`XDG_RUNTIME_DIR` if defined, otherwise :file:`/run/user/<uid>` if
|
||||
accessible, falling back to the :file:`run` directory inside the kitty
|
||||
cache directory.
|
||||
Contrôle l'endroit où kitty stocke les fichiers d'exécution comme les
|
||||
sockets. Sous macOS, la valeur par défaut est le dossier de cache natif par
|
||||
utilisateur renvoyé par :code:`getconf DARWIN_USER_CACHE_DIR`. Sur les
|
||||
autres plateformes, kitty utilise :code:`XDG_RUNTIME_DIR` s'il est défini,
|
||||
sinon :file:`/run/user/<uid>` s'il est accessible, et se rabat sur le
|
||||
dossier :file:`run` à l'intérieur du dossier de cache de kitty.
|
||||
|
||||
.. envvar:: VISUAL
|
||||
|
||||
The terminal based text editor (such as :program:`vi` or :program:`nano`)
|
||||
kitty uses, when, for instance, opening :file:`kitty.conf` in response to
|
||||
:sc:`edit_config_file`.
|
||||
L'éditeur de texte en mode terminal (comme :program:`vi` ou
|
||||
:program:`nano`) utilisé par kitty, par exemple pour ouvrir
|
||||
:file:`kitty.conf` en réponse à :sc:`edit_config_file`.
|
||||
|
||||
.. envvar:: EDITOR
|
||||
|
||||
Same as :envvar:`VISUAL`. Used if :envvar:`VISUAL` is not set.
|
||||
Identique à :envvar:`VISUAL`. Utilisée si :envvar:`VISUAL` n'est pas
|
||||
définie.
|
||||
|
||||
.. envvar:: SHELL
|
||||
|
||||
Specifies the default shell kitty will run when :opt:`shell` is set to
|
||||
Indique le shell par défaut que kitty lancera lorsque :opt:`shell` vaut
|
||||
:code:`.`.
|
||||
|
||||
.. envvar:: GLFW_IM_MODULE
|
||||
|
||||
Set this to ``ibus`` to enable support for IME under X11.
|
||||
Mettez-la à ``ibus`` pour activer la prise en charge de l'IME sous X11.
|
||||
|
||||
.. envvar:: KITTY_WAYLAND_DETECT_MODIFIERS
|
||||
|
||||
When set to a non-empty value, kitty attempts to autodiscover XKB modifiers
|
||||
under Wayland. This is useful if using non-standard modifiers like hyper. It
|
||||
is possible for the autodiscovery to fail; the default Wayland XKB mappings
|
||||
are used in this case. See :pull:`3943` for details.
|
||||
Lorsqu'elle est définie à une valeur non vide, kitty tente de découvrir
|
||||
automatiquement les modificateurs XKB sous Wayland. C'est utile si vous
|
||||
utilisez des modificateurs non standard comme hyper. La découverte
|
||||
automatique peut échouer ; les associations XKB Wayland par défaut sont
|
||||
alors utilisées. Voir :pull:`3943` pour les détails.
|
||||
|
||||
.. envvar:: SSH_ASKPASS
|
||||
|
||||
Specify the program for SSH to ask for passwords. When this is set, :doc:`ssh
|
||||
kitten </kittens/ssh>` will use this environment variable by default. See
|
||||
:opt:`askpass <kitten-ssh.askpass>` for details.
|
||||
Indique le programme que SSH utilise pour demander les mots de passe.
|
||||
Lorsqu'elle est définie, :doc:`le kitten ssh </kittens/ssh>` utilisera cette
|
||||
variable d'environnement par défaut. Voir :opt:`askpass <kitten-ssh.askpass>`
|
||||
pour les détails.
|
||||
|
||||
.. envvar:: KITTY_CLONE_SOURCE_CODE
|
||||
|
||||
Set this to some shell code that will be executed in the cloned window with
|
||||
:code:`eval` when :ref:`clone-in-kitty <clone_shell>` is used.
|
||||
Définissez-la avec du code shell qui sera exécuté avec :code:`eval` dans la
|
||||
fenêtre clonée lorsque :ref:`clone-in-kitty <clone_shell>` est utilisé.
|
||||
|
||||
.. envvar:: KITTY_CLONE_SOURCE_PATH
|
||||
|
||||
Set this to the path of a file that will be sourced in the cloned window when
|
||||
:ref:`clone-in-kitty <clone_shell>` is used.
|
||||
Définissez-la avec le chemin d'un fichier qui sera sourcé dans la fenêtre
|
||||
clonée lorsque :ref:`clone-in-kitty <clone_shell>` est utilisé.
|
||||
|
||||
.. envvar:: KITTY_DEVELOP_FROM
|
||||
|
||||
Set this to the directory path of the kitty source code and its Python code
|
||||
will be loaded from there. Only works with official binary builds.
|
||||
Définissez-la avec le chemin du dossier des sources de kitty pour que son
|
||||
code Python soit chargé depuis là. Ne fonctionne qu'avec les compilations
|
||||
binaires officielles.
|
||||
|
||||
.. envvar:: KITTY_RC_PASSWORD
|
||||
|
||||
Set this to a pass phrase to use the ``kitten @`` remote control command with
|
||||
:opt:`remote_control_password`.
|
||||
Définissez-la avec une phrase de passe pour utiliser la commande de contrôle
|
||||
à distance ``kitten @`` avec :opt:`remote_control_password`.
|
||||
|
||||
|
||||
Variables that kitty sets when running child programs
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
Variables que kitty définit en lançant des programmes enfants
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. envvar:: LANG
|
||||
|
||||
This is only set on macOS. If the country and language from the macOS user
|
||||
settings form an invalid locale, it will be set to :code:`en_US.UTF-8`.
|
||||
Définie uniquement sous macOS. Si le pays et la langue des réglages
|
||||
utilisateur de macOS forment une locale invalide, elle est définie à
|
||||
:code:`en_US.UTF-8`.
|
||||
|
||||
.. envvar:: PATH
|
||||
|
||||
kitty prepends itself to the PATH of its own environment to ensure the
|
||||
functions calling :program:`kitty` will work properly.
|
||||
kitty s'ajoute en tête du PATH de son propre environnement afin que les
|
||||
fonctions appelant :program:`kitty` fonctionnent correctement.
|
||||
|
||||
.. envvar:: KITTY_WINDOW_ID
|
||||
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
|
||||
contrôle à distance de kitty <remote-control>`.
|
||||
|
||||
An integer that is the id for the kitty :term:`window` the program is running in.
|
||||
Can be used with the :doc:`kitty remote control facility <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
|
||||
|
||||
An integer that is the process id for the kitty process in which the program
|
||||
is running. Allows programs to tell kitty to reload its config by sending it
|
||||
the SIGUSR1 signal.
|
||||
Un entier qui est l'identifiant du processus kitty dans lequel le programme
|
||||
s'exécute. Permet aux programmes de demander à kitty de recharger sa
|
||||
configuration en lui envoyant le signal SIGUSR1.
|
||||
|
||||
.. envvar:: KITTY_PUBLIC_KEY
|
||||
|
||||
A public key that programs can use to communicate securely with kitty using
|
||||
the remote control protocol. The format is: :code:`protocol:key data`.
|
||||
Une clé publique que les programmes peuvent utiliser pour communiquer de
|
||||
façon sécurisée avec kitty via le protocole de contrôle à distance. Le
|
||||
format est : :code:`protocol:key data`.
|
||||
|
||||
.. envvar:: WINDOWID
|
||||
|
||||
The id for the :term:`OS Window <os_window>` the program is running in. Only available
|
||||
on platforms that have ids for their windows, such as X11 and macOS.
|
||||
L'identifiant de la :term:`fenêtre OS <os_window>` dans laquelle le
|
||||
programme s'exécute. Disponible uniquement sur les plateformes ayant des
|
||||
identifiants de fenêtre, comme X11 et macOS.
|
||||
|
||||
.. envvar:: TERM
|
||||
|
||||
The name of the terminal, defaults to ``xterm-kitty``. See :opt:`term`.
|
||||
Le nom du terminal, par défaut ``xterm-kitty``. Voir :opt:`term`.
|
||||
|
||||
.. envvar:: TERMINFO
|
||||
|
||||
Path to a directory containing the kitty terminfo database. Or the terminfo
|
||||
database itself encoded in base64. See :opt:`terminfo_type`.
|
||||
Chemin d'un dossier contenant la base terminfo de kitty. Ou la base terminfo
|
||||
elle-même encodée en base64. Voir :opt:`terminfo_type`.
|
||||
|
||||
.. envvar:: KITTY_INSTALLATION_DIR
|
||||
|
||||
Path to the kitty installation directory.
|
||||
Chemin du dossier d'installation de kitty.
|
||||
|
||||
.. envvar:: COLORTERM
|
||||
|
||||
Set to the value ``truecolor`` to indicate that kitty supports 16 million
|
||||
colors.
|
||||
Définie à la valeur ``truecolor`` pour indiquer que kitty prend en charge 16
|
||||
millions de couleurs.
|
||||
|
||||
.. envvar:: KITTY_LISTEN_ON
|
||||
|
||||
Set when the :doc:`remote control <remote-control>` facility is enabled and
|
||||
the a socket is used for control via :option:`kitty --listen-on` or :opt:`listen_on`.
|
||||
Contains the path to the socket. Avoid the need to use :option:`kitten @ --to` when
|
||||
issuing remote control commands. Can also be a file descriptor of the form
|
||||
fd:num instead of a socket address, in which case, remote control
|
||||
communication should proceed over the specified file descriptor.
|
||||
Définie lorsque la :doc:`facilité de contrôle à distance <remote-control>`
|
||||
est activée et qu'un socket est utilisé pour le contrôle via
|
||||
:option:`kitty --listen-on` ou :opt:`listen_on`. Contient le chemin du
|
||||
socket. Évite d'avoir à utiliser :option:`kitten @ --to` en émettant des
|
||||
commandes de contrôle à distance. Peut aussi être un descripteur de fichier
|
||||
de la forme fd:num au lieu d'une adresse de socket, auquel cas la
|
||||
communication de contrôle à distance doit passer par le descripteur de
|
||||
fichier indiqué.
|
||||
|
||||
.. envvar:: KITTY_PIPE_DATA
|
||||
|
||||
Set to data describing the layout of the screen when running child
|
||||
programs using :option:`launch --stdin-source` with the contents of the
|
||||
screen/scrollback piped to them.
|
||||
Définie avec les données décrivant l'agencement de l'écran lors de
|
||||
l'exécution de programmes enfants avec :option:`launch --stdin-source`, le
|
||||
contenu de l'écran et de l'historique leur étant envoyé.
|
||||
|
||||
.. envvar:: KITTY_CHILD_CMDLINE
|
||||
|
||||
Set to the command line of the child process running in the kitty
|
||||
window when calling the notification callback program on terminal bell, see
|
||||
:opt:`command_on_bell`.
|
||||
Définie avec la ligne de commande du processus enfant qui s'exécute dans la
|
||||
fenêtre kitty lors de l'appel du programme de notification sur sonnerie du
|
||||
terminal, voir :opt:`command_on_bell`.
|
||||
|
||||
.. envvar:: KITTY_COMMON_OPTS
|
||||
|
||||
Set with the values of some common kitty options when running
|
||||
kittens, so kittens can use them without needing to load :file:`kitty.conf`.
|
||||
Définie avec les valeurs de quelques options courantes de kitty lors de
|
||||
l'exécution de kittens, afin qu'ils puissent les utiliser sans avoir à
|
||||
charger :file:`kitty.conf`.
|
||||
|
||||
.. envvar:: KITTY_SHELL_INTEGRATION
|
||||
|
||||
Set when enabling :ref:`shell_integration`. It is automatically removed by
|
||||
the shell integration scripts.
|
||||
Définie lors de l'activation de :ref:`shell_integration`. Elle est
|
||||
automatiquement supprimée par les scripts d'intégration du shell.
|
||||
|
||||
.. envvar:: KITTY_SI_RUN_COMMAND_AT_STARTUP
|
||||
|
||||
Set this to an expression that the kitty shell integration scripts will
|
||||
``eval`` after the shell is started. Note that this environment variable
|
||||
is ignored when present in the environment in which kitty itself is launched
|
||||
in. It is most useful with the ``--env`` flag for the :doc:`launch <launch>`
|
||||
action.
|
||||
Définissez-la avec une expression que les scripts d'intégration du shell de
|
||||
kitty évalueront avec ``eval`` après le démarrage du shell. Notez que cette
|
||||
variable est ignorée lorsqu'elle est présente dans l'environnement dans
|
||||
lequel kitty lui-même est lancé. Elle est surtout utile avec l'option
|
||||
``--env`` de l'action :doc:`launch <launch>`.
|
||||
|
||||
.. envvar:: ZDOTDIR
|
||||
|
||||
Set when enabling :ref:`shell_integration` with :program:`zsh`, allowing
|
||||
:program:`zsh` to automatically load the integration script.
|
||||
Définie lors de l'activation de :ref:`shell_integration` avec
|
||||
:program:`zsh`, ce qui permet à :program:`zsh` de charger automatiquement le
|
||||
script d'intégration.
|
||||
|
||||
.. envvar:: XDG_DATA_DIRS
|
||||
|
||||
Set when enabling :ref:`shell_integration` with :program:`fish`, allowing
|
||||
:program:`fish` to automatically load the integration script.
|
||||
Définie lors de l'activation de :ref:`shell_integration` avec
|
||||
:program:`fish`, ce qui permet à :program:`fish` de charger automatiquement
|
||||
le script d'intégration.
|
||||
|
||||
.. envvar:: ENV
|
||||
|
||||
Set when enabling :ref:`shell_integration` with :program:`bash`, allowing
|
||||
:program:`bash` to automatically load the integration script.
|
||||
Définie lors de l'activation de :ref:`shell_integration` avec
|
||||
:program:`bash`, ce qui permet à :program:`bash` de charger automatiquement
|
||||
le script d'intégration.
|
||||
|
||||
.. envvar:: KITTY_OS
|
||||
|
||||
Set when using the include directive in kitty.conf. Can take values:
|
||||
``linux``, ``macos``, ``bsd``.
|
||||
Définie lors de l'utilisation de la directive include dans kitty.conf. Peut
|
||||
prendre les valeurs : ``linux``, ``macos``, ``bsd``.
|
||||
|
||||
.. envvar:: KITTY_HOLD
|
||||
|
||||
Set to ``1`` when kitty is running a shell because of the ``--hold`` flag. Can
|
||||
be used to specialize shell behavior in the shell rc files as desired.
|
||||
Définie à ``1`` lorsque kitty exécute un shell à cause de l'option
|
||||
``--hold``. Peut servir à spécialiser le comportement du shell dans les
|
||||
fichiers rc du shell selon vos besoins.
|
||||
|
||||
.. envvar:: KITTY_SIMD
|
||||
|
||||
Set it to ``128`` to use 128 bit vector registers, ``256`` to use 256 bit
|
||||
vector registers, or ``512`` to use AVX-512 on x86-64. Any other value
|
||||
prevents kitty from using SIMD CPU vector instructions. Warning, this
|
||||
overrides CPU capability detection so will cause kitty to crash with SIGILL
|
||||
if your CPU does not support the necessary SIMD extensions.
|
||||
Mettez-la à ``128`` pour utiliser des registres vectoriels de 128 bits,
|
||||
``256`` pour des registres de 256 bits, ou ``512`` pour utiliser AVX-512 sur
|
||||
x86-64. Toute autre valeur empêche kitty d'utiliser les instructions
|
||||
vectorielles SIMD du processeur. Attention, cela outrepasse la détection des
|
||||
capacités du processeur et fera planter kitty avec SIGILL si votre
|
||||
processeur ne prend pas en charge les extensions SIMD nécessaires.
|
||||
@@ -18,6 +18,7 @@ The fast, feature-rich, GPU based terminal emulator.
|
||||
integrations
|
||||
protocol-extensions
|
||||
custom-shaders
|
||||
accessibility
|
||||
press-mentions
|
||||
|
||||
|
||||
|
||||
+4
-4
@@ -1,7 +1,7 @@
|
||||
:orphan:
|
||||
|
||||
The kitty command line interface
|
||||
====================================
|
||||
L'interface en ligne de commande de kitty
|
||||
=========================================
|
||||
|
||||
.. program:: kitty
|
||||
|
||||
@@ -9,7 +9,7 @@ The kitty command line interface
|
||||
|
||||
.. include:: basic.rst
|
||||
|
||||
See also
|
||||
Voir aussi
|
||||
-----------
|
||||
|
||||
See kitty.conf(5)
|
||||
Voir kitty.conf(5)
|
||||
@@ -88,9 +88,9 @@ The following keys are available while the command palette is open:
|
||||
- Run the selected action
|
||||
* - :kbd:`Escape`
|
||||
- Clear the search query, or close the palette if the query is already empty
|
||||
* - :kbd:`Up` / :kbd:`Ctrl+K` / :kbd:`Ctrl+P`
|
||||
* - :kbd:`Up` / :kbd:`Shift+Tab` / :kbd:`Ctrl+K` / :kbd:`Ctrl+P`
|
||||
- Move selection up
|
||||
* - :kbd:`Down` / :kbd:`Ctrl+J` / :kbd:`Ctrl+N`
|
||||
* - :kbd:`Down` / :kbd:`Tab` / :kbd:`Ctrl+J` / :kbd:`Ctrl+N`
|
||||
- Move selection down
|
||||
* - :kbd:`Page Up`
|
||||
- Move selection up by a page
|
||||
@@ -102,12 +102,38 @@ The following keys are available while the command palette is open:
|
||||
- Jump to the last result
|
||||
* - :kbd:`Backspace`
|
||||
- Delete the last character from the query
|
||||
* - :kbd:`Ctrl+R`
|
||||
- Remap the selected action by pressing its new shortcut
|
||||
* - :kbd:`F12`
|
||||
- Toggle display of unmapped actions
|
||||
* - Mouse click
|
||||
- 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
|
||||
------------------
|
||||
|
||||
|
||||
@@ -0,0 +1,254 @@
|
||||
.. _file_manager:
|
||||
|
||||
Gestionnaire de fichiers
|
||||
=========================
|
||||
|
||||
.. only:: man
|
||||
|
||||
Aperçu
|
||||
------
|
||||
|
||||
Le gestionnaire de fichiers affiche le contenu d'un répertoire dans un panneau
|
||||
latéral, pilotable entièrement au clavier, et change le répertoire courant du
|
||||
shell qui l'a lancé. Il remplace la plupart des :code:`cd` : on descend dans
|
||||
l'arborescence avec :kbd:`Entrée`, puis :kbd:`Ctrl+Entrée` ferme le panneau et
|
||||
déplace le shell, sans perdre l'environnement, l'historique ni l'état de la
|
||||
session.
|
||||
|
||||
Le raccourci par défaut :kbd:`Ctrl+Shift+E` ouvre le panneau dans un
|
||||
:ref:`dock <docks>` à gauche de la fenêtre courante. On peut aussi le lancer
|
||||
avec :code:`kitten file-manager`, ou depuis une :ref:`fenêtre dockée <docks>`
|
||||
pour l'avoir en permanence à côté du shell. Pour changer le raccourci ou le type
|
||||
de lancement, redéfinissez-le dans :file:`kitty.conf`::
|
||||
|
||||
map ctrl+shift+e launch --type=overlay kitten file-manager
|
||||
|
||||
Il peut aussi tourner dans un :doc:`panneau du bureau </kittens/panel>` ou dans
|
||||
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
|
||||
est passé en argument ou avec ``--start-dir``. Un chemin commençant par ``~``
|
||||
y est développé, même lorsqu'il vient d'un mappage où le shell ne l'a pas fait.
|
||||
|
||||
.. note::
|
||||
|
||||
Le changement de répertoire ne peut viser que la fenêtre depuis laquelle le
|
||||
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
|
||||
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
|
||||
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
|
||||
fichier à kitty, qui lance l'éditeur dans un nouvel onglet. Le fichier
|
||||
dispose ainsi de toute la fenêtre même depuis un dock, et le panneau reprend
|
||||
la main à la fermeture de l'éditeur, avec la même sélection.
|
||||
|
||||
|
||||
Actions
|
||||
-------
|
||||
|
||||
:kbd:`Entrée`
|
||||
Si la sélection est un répertoire, le panneau y descend, exactement comme
|
||||
avec :kbd:`→`. Si c'est un fichier, il est ouvert dans l'éditeur de kitty
|
||||
(:opt:`editor`, :envvar:`VISUAL` ou :envvar:`EDITOR`) dans un nouvel onglet ;
|
||||
le panneau reste ouvert et retrouve sa sélection lorsque l'éditeur se ferme.
|
||||
|
||||
Le nouvel onglet est ce qui donne au fichier toute la fenêtre : dans un
|
||||
dock, exécuter l'éditeur dans le panneau le réduirait à la largeur du dock.
|
||||
L'édition passe par le protocole d'édition de kitty, le fichier doit donc
|
||||
être accessible en lecture et en écriture ; pour un fichier de root,
|
||||
utilisez :code:`sudo -e` depuis le shell.
|
||||
|
||||
:kbd:`→` ou :kbd:`L`
|
||||
descend dans le répertoire sélectionné ; le shell y va aussi, au prompt
|
||||
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`
|
||||
remonte au répertoire parent.
|
||||
|
||||
:kbd:`Ctrl+Entrée` ou :kbd:`C`
|
||||
déplace le shell vers la sélection si c'est un répertoire, sinon vers le
|
||||
répertoire affiché, puis ferme le panneau.
|
||||
|
||||
:kbd:`Tab` et :kbd:`Maj+Tab`
|
||||
passent à l'entrée suivante, respectivement précédente, comme :kbd:`↓` et
|
||||
:kbd:`↑`. Pendant la saisie d'un nom, la tabulation est ignorée : elle ne
|
||||
peut pas faire partie d'un nom de fichier.
|
||||
|
||||
:kbd:`/`
|
||||
filtre la liste à mesure de la saisie, avec la même recherche floue que la
|
||||
palette de commandes. :kbd:`Entrée` ouvre la sélection, :kbd:`Échap`
|
||||
efface la requête et rétablit la liste complète. Un nom de répertoire suivi
|
||||
d'un :code:`/` ne filtre que les répertoires ; la requête est oubliée en
|
||||
changeant de répertoire.
|
||||
|
||||
:kbd:`:`
|
||||
ouvre la palette des actions. Elle liste chaque action avec sa description,
|
||||
se filtre comme la recherche, et :kbd:`Entrée` exécute l'action
|
||||
sélectionnée. La liste est la source unique utilisée par ce document :
|
||||
toutes les actions configurables y figurent.
|
||||
|
||||
:kbd:`O` et :kbd:`T`
|
||||
ouvrent le fichier sélectionné dans un nouvel onglet, respectivement une
|
||||
nouvelle fenêtre du système. Sur un répertoire, elles y entrent sans
|
||||
toucher au répertoire du shell.
|
||||
|
||||
:kbd:`N` et :kbd:`Maj+N`
|
||||
créent un fichier, respectivement un répertoire, dans le répertoire
|
||||
affiché. Le nom se saisit dans la ligne d'état. :kbd:`A` est un alias de
|
||||
:kbd:`Maj+N`, pour les claviers où la combinaison est peu pratique.
|
||||
|
||||
:kbd:`R`
|
||||
renomme l'entrée sélectionnée.
|
||||
|
||||
:kbd:`D`
|
||||
supprime l'entrée sélectionnée après confirmation par :kbd:`y`. Les
|
||||
répertoires ne sont jamais supprimés récursivement : un répertoire non vide
|
||||
provoque une erreur.
|
||||
|
||||
:kbd:`Y`
|
||||
copie le chemin de la sélection dans le presse-papiers.
|
||||
|
||||
:kbd:`.`
|
||||
affiche ou masque les entrées cachées.
|
||||
|
||||
:kbd:`Échap` ou :kbd:`Q`
|
||||
ferme le panneau sans rien changer : une demande de synchronisation que le
|
||||
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:
|
||||
|
||||
Raccourcis et configuration
|
||||
-----------------------------
|
||||
|
||||
Tous les raccourcis sont configurables dans :file:`file-manager.conf`, dans le
|
||||
répertoire de configuration de kitty, avec la même syntaxe que les mappages de
|
||||
:file:`kitty.conf`. La valeur par défaut, suivie d'un exemple de
|
||||
personnalisation::
|
||||
|
||||
# ~/.config/kitty/file-manager.conf
|
||||
show_hidden yes
|
||||
sort_by mtime
|
||||
map quit esc quit
|
||||
map toggle_hidden ctrl+h toggle_hidden
|
||||
map delete x delete
|
||||
|
||||
Les actions disponibles sont :code:`quit`, :code:`move_up`, :code:`move_down`,
|
||||
:code:`page_up`, :code:`page_down`, :code:`home`, :code:`end`,
|
||||
:code:`activate`, :code:`enter_dir`, :code:`parent_dir`, :code:`cd_here`,
|
||||
:code:`toggle_hidden`, :code:`create_file`, :code:`create_dir`,
|
||||
:code:`rename`, :code:`delete`, :code:`copy_path`, :code:`refresh`,
|
||||
:code:`search`, :code:`palette`, :code:`open_tab` et :code:`open_window`.
|
||||
:code:`search`, :code:`palette`, :code:`open_tab` et :code:`open_window` sont
|
||||
les actions des raccourcis :kbd:`/`, :kbd:`:`, :kbd:`O` et :kbd:`T`.
|
||||
La palette :kbd:`:` liste ces actions avec leur description, ce qui évite de
|
||||
retourner à ce document pour retrouver un nom.
|
||||
|
||||
Deux réglages d'apparence sont aussi disponibles : ``show_hidden`` affiche les
|
||||
entrées cachées à l'ouverture du panneau et ``sort_by`` vaut ``name`` (tri par
|
||||
nom en ignorant la casse), ``mtime`` (tri par date de dernière modification) ou
|
||||
``size`` (tri par taille, du plus gros au plus petit).
|
||||
Les deux réglages peuvent être changés pour la session courante avec
|
||||
:code:`-o show_hidden=yes` et :code:`-o sort_by=mtime`, ou :code:`-o sort_by=size`.
|
||||
|
||||
L'éditeur n'est pas choisi par le panneau : le fichier est confié à kitty, qui
|
||||
utilise son option :opt:`editor` de :file:`kitty.conf`. Quand celle-ci vaut
|
||||
:code:`.` (le défaut), :envvar:`VISUAL` puis :envvar:`EDITOR` sont utilisés,
|
||||
avec repli sur le premier éditeur connu installé. Pour forcer nano, ajoutez
|
||||
:code:`editor nano` dans :file:`kitty.conf`.
|
||||
|
||||
Intégration au shell
|
||||
---------------------
|
||||
|
||||
Le panneau ne lance pas de shell : il écrit dans le terminal de la fenêtre qui
|
||||
l'a lancé. Lorsque le shell est au prompt (fin d'OSC :code:`133`), la commande
|
||||
:code:`cd` est envoyée directement, comme si elle avait été tapée. Lorsqu'un
|
||||
programme tourne, le texte est seulement collé, pour qu'il puisse être relu
|
||||
plutôt que de tomber dans l'entrée standard de ce programme. L'intégration du
|
||||
shell doit donc être active : elle l'est par défaut pour bash, zsh et fish
|
||||
lancés par kitty.
|
||||
|
||||
Le répertoire de travail est transmis à la fenêtre d'origine uniquement, et
|
||||
seulement pour les shells qui comprennent :code:`cd` avec un chemin entre
|
||||
guillemets simples, c'est-à-dire les shells de type POSIX. Dans :code:`cmd.exe`
|
||||
ou PowerShell, le panneau reste utilisable pour naviguer et ouvrir des fichiers,
|
||||
mais la validation d'un répertoire ne change pas le répertoire courant.
|
||||
|
||||
Limites
|
||||
-------
|
||||
|
||||
- Aucun aperçu du contenu des fichiers : seul le nom, le type et la date de
|
||||
dernière modification sont affichés.
|
||||
- Aucun montage ni démontage de volume, et aucune corbeille : la suppression est
|
||||
immédiate, après confirmation.
|
||||
- La suppression n'est jamais récursive ; un répertoire non vide provoque une
|
||||
erreur.
|
||||
- Les fichiers appartenant à root ne peuvent pas être ouverts : l'édition passe
|
||||
par kitty et demande un accès en lecture et en écriture. Utilisez
|
||||
:code:`sudo -e` depuis le shell.
|
||||
- Lancé dans un dock ou un panneau du bureau, le panneau n'a pas de shell cible
|
||||
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 :
|
||||
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/cli-kitten-file_manager.rst
|
||||
@@ -0,0 +1,55 @@
|
||||
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.
|
||||
+68
-50
@@ -1,7 +1,7 @@
|
||||
.. _kittens:
|
||||
|
||||
Extend with kittens
|
||||
-----------------------
|
||||
Étendre avec les kittens
|
||||
------------------------
|
||||
|
||||
.. toctree::
|
||||
:hidden:
|
||||
@@ -14,10 +14,12 @@ Extend with kittens
|
||||
kittens/choose-fonts
|
||||
kittens/hints
|
||||
kittens/command-palette
|
||||
kittens/help
|
||||
kittens/quick-access-terminal
|
||||
kittens/choose-files
|
||||
kittens/dnd
|
||||
kittens/panel
|
||||
kittens/file-manager
|
||||
kittens/remote_file
|
||||
kittens/hyperlinked_grep
|
||||
kittens/transfer
|
||||
@@ -25,89 +27,105 @@ Extend with kittens
|
||||
kittens/custom
|
||||
kittens/*
|
||||
|
||||
|kitty| has a framework for easily creating terminal programs that make use of
|
||||
its advanced features. These programs are called kittens. They are used both to
|
||||
add features to |kitty| itself and to create useful standalone programs.
|
||||
Some prominent kittens:
|
||||
|kitty| dispose d'un framework pour créer facilement des programmes de terminal
|
||||
tirant parti de ses fonctionnalités avancées. Ces programmes sont appelés des
|
||||
kittens. Ils servent à la fois à ajouter des fonctionnalités à |kitty| lui-même
|
||||
et à créer des programmes autonomes utiles. Quelques kittens importants :
|
||||
|
||||
:doc:`icat <kittens/icat>`
|
||||
Display images in the terminal.
|
||||
Affiche des images dans le terminal.
|
||||
|
||||
|
||||
:doc:`diff <kittens/diff>`
|
||||
A fast, side-by-side diff for the terminal with syntax highlighting and
|
||||
Un diff côte à côte rapide pour le terminal, avec coloration syntaxique et
|
||||
images.
|
||||
|
||||
|
||||
:doc:`Unicode input <kittens/unicode_input>`
|
||||
Easily input arbitrary Unicode characters in |kitty| by name or hex code.
|
||||
:doc:`Saisie Unicode <kittens/unicode_input>`
|
||||
Saisit facilement des caractères Unicode arbitraires dans |kitty| par nom ou
|
||||
par code hexadécimal.
|
||||
|
||||
|
||||
:doc:`Themes <kittens/themes>`
|
||||
Preview and quick switch between over three hundred color themes.
|
||||
:doc:`Thèmes <kittens/themes>`
|
||||
Prévisualisez et passez rapidement d'un thème à l'autre parmi plus de trois
|
||||
cents thèmes de couleurs.
|
||||
|
||||
|
||||
:doc:`Fonts <kittens/choose-fonts>`
|
||||
Preview, fine-tune and quick switch the fonts used by kitty.
|
||||
:doc:`Polices <kittens/choose-fonts>`
|
||||
Prévisualisez, ajustez finement et changez rapidement les polices utilisées
|
||||
par kitty.
|
||||
|
||||
|
||||
:doc:`Hints <kittens/hints>`
|
||||
Select and open/paste/insert arbitrary text snippets such as URLs,
|
||||
filenames, words, lines, etc. from the terminal screen.
|
||||
:doc:`Indices <kittens/hints>`
|
||||
Sélectionnez et ouvrez, collez ou insérez des extraits de texte arbitraires
|
||||
tels que des URL, des noms de fichiers, des mots, des lignes, etc. depuis
|
||||
l'écran du terminal.
|
||||
|
||||
|
||||
:doc:`Command palette <kittens/command-palette>`
|
||||
Browse, search and trigger all keyboard shortcuts and actions from a
|
||||
single searchable overlay.
|
||||
:doc:`Palette de commandes <kittens/command-palette>`
|
||||
Parcourez, cherchez et déclenchez tous les raccourcis clavier et actions
|
||||
depuis une seule surcouche de recherche.
|
||||
|
||||
|
||||
:doc:`Quick access terminal <kittens/quick-access-terminal>`
|
||||
Get access to a quick access floating, semi-transparent kitty window
|
||||
with a single keypress.
|
||||
: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:`Panel <kittens/panel>`
|
||||
Draw the desktop wallpaper or docks and panels using arbitrary
|
||||
terminal programs.
|
||||
:doc:`Terminal à accès rapide <kittens/quick-access-terminal>`
|
||||
Accédez à une fenêtre kitty flottante et semi-transparente d'accès rapide
|
||||
avec une seule combinaison de touches.
|
||||
|
||||
|
||||
:doc:`Choose files <kittens/choose-files>`
|
||||
Preview and select files at the speed of thought
|
||||
:doc:`Panneau <kittens/panel>`
|
||||
Dessinez le fond d'écran du bureau ou des docks et panneaux à l'aide de
|
||||
programmes de terminal arbitraires.
|
||||
|
||||
|
||||
:doc:`Drag and drop from the shell <kittens/dnd>`
|
||||
Drag and drop files from/to GUI programs from your shell, even over SSH
|
||||
:doc:`Choisir des fichiers <kittens/choose-files>`
|
||||
Prévisualisez et sélectionnez des fichiers à la vitesse de la pensée
|
||||
|
||||
|
||||
:doc:`Remote file <kittens/remote_file>`
|
||||
Edit, open, or download remote files over SSH easily, by simply clicking on
|
||||
the filename.
|
||||
:doc:`Glisser-déposer depuis le shell <kittens/dnd>`
|
||||
Glissez-déposez des fichiers depuis et vers des programmes graphiques depuis
|
||||
votre shell, même via SSH
|
||||
|
||||
|
||||
:doc:`Transfer files <kittens/transfer>`
|
||||
Transfer files and directories seamlessly and easily from remote machines
|
||||
over your existing SSH sessions with a simple command.
|
||||
:doc:`Fichiers distants <kittens/remote_file>`
|
||||
Éditez, ouvrez ou téléchargez facilement des fichiers distants via SSH, en
|
||||
cliquant simplement sur le nom du fichier.
|
||||
|
||||
|
||||
:doc:`Hyperlinked grep <kittens/hyperlinked_grep>`
|
||||
Search your files using `ripgrep <https://github.com/BurntSushi/ripgrep>`__
|
||||
and open the results directly in your favorite editor in the terminal,
|
||||
at the line containing the search result, simply by clicking on the result
|
||||
you want.
|
||||
:doc:`Transférer des fichiers <kittens/transfer>`
|
||||
Transférez sans effort des fichiers et des dossiers depuis des machines
|
||||
distantes via vos sessions SSH existantes, avec une simple commande.
|
||||
|
||||
|
||||
:doc:`Broadcast <kittens/broadcast>`
|
||||
Type in one :term:`kitty window <window>` and have it broadcast to all (or a
|
||||
subset) of other :term:`kitty windows <window>`.
|
||||
:doc:`grep avec liens <kittens/hyperlinked_grep>`
|
||||
Cherchez dans vos fichiers avec `ripgrep
|
||||
<https://github.com/BurntSushi/ripgrep>`__ et ouvrez les résultats
|
||||
directement dans votre éditeur préféré en mode terminal, à la ligne
|
||||
contenant le résultat, en cliquant simplement sur le résultat voulu.
|
||||
|
||||
|
||||
:doc:`Diffusion <kittens/broadcast>`
|
||||
Tapez dans une :term:`fenêtre kitty <window>` et faites-le diffuser vers
|
||||
toutes les autres :term:`fenêtres kitty <window>` (ou une partie d'entre
|
||||
elles).
|
||||
|
||||
|
||||
:doc:`SSH <kittens/ssh>`
|
||||
SSH with automatic :ref:`shell integration <shell_integration>`, connection
|
||||
re-use for low latency and easy cloning of local shell and editor
|
||||
configuration to the remote host.
|
||||
SSH avec :ref:`intégration du shell <shell_integration>` automatique,
|
||||
réutilisation de la connexion pour une faible latence et clonage facile de
|
||||
la configuration locale du shell et de l'éditeur vers l'hôte distant.
|
||||
|
||||
|
||||
:doc:`Clipboard <kittens/clipboard>`
|
||||
Copy/paste to the clipboard from shell scripts, even over SSH.
|
||||
:doc:`Presse-papiers <kittens/clipboard>`
|
||||
Copiez/collez dans le presse-papiers depuis des scripts shell, même via SSH.
|
||||
|
||||
You can also :doc:`Learn to create your own kittens <kittens/custom>`.
|
||||
|
||||
:doc:`Gestionnaire de fichiers <kittens/file-manager>`
|
||||
Parcourez les répertoires dans un panneau latéral et changez le répertoire
|
||||
courant du shell sans quitter celui-ci.
|
||||
|
||||
Vous pouvez aussi :doc:`apprendre à créer vos propres kittens <kittens/custom>`.
|
||||
+127
-113
@@ -1,128 +1,139 @@
|
||||
The :command:`launch` command
|
||||
La commande :command:`launch`
|
||||
--------------------------------
|
||||
|
||||
.. program:: launch
|
||||
|
||||
|
||||
|kitty| has a :code:`launch` action that can be used to run arbitrary programs
|
||||
in new windows/tabs. It can be mapped to user defined shortcuts in
|
||||
:file:`kitty.conf`. It is very powerful and allows sending the contents of the
|
||||
current window to the launched program, as well as many other options.
|
||||
|kitty| dispose d'une action :code:`launch` qui permet de lancer des programmes
|
||||
arbitraires dans de nouvelles fenêtres ou de nouveaux onglets. Elle peut être
|
||||
associée à des raccourcis définis par l'utilisateur dans :file:`kitty.conf`.
|
||||
Elle est très puissante et permet d'envoyer le contenu de la fenêtre courante au
|
||||
programme lancé, ainsi que bien d'autres options.
|
||||
|
||||
In the simplest form, you can use it to open a new kitty window running the
|
||||
shell, as shown below::
|
||||
Dans sa forme la plus simple, vous pouvez l'utiliser pour ouvrir une nouvelle
|
||||
fenêtre kitty exécutant le shell, comme montré ci-dessous ::
|
||||
|
||||
map f1 launch
|
||||
|
||||
To run a different program simply pass the command line as arguments to launch::
|
||||
Pour lancer un autre programme, passez simplement la ligne de commande en
|
||||
arguments à launch ::
|
||||
|
||||
map f1 launch vim path/to/some/file
|
||||
|
||||
To open a new window with the same working directory as the currently active
|
||||
window::
|
||||
Pour ouvrir une nouvelle fenêtre dans le même répertoire de travail que la
|
||||
fenêtre actuellement active ::
|
||||
|
||||
map f1 launch --cwd=current
|
||||
|
||||
To open the new window in a new tab::
|
||||
Pour ouvrir la nouvelle fenêtre dans un nouvel onglet ::
|
||||
|
||||
map f1 launch --type=tab
|
||||
|
||||
To open a window docked to the bottom of the active window, using ten lines,
|
||||
see :ref:`docks`::
|
||||
Pour ouvrir une fenêtre ancrée en bas de la fenêtre active, sur dix lignes, voir
|
||||
:ref:`docks` ::
|
||||
|
||||
map f1 launch --type=window-dock --dock-edge=bottom --dock-size=10
|
||||
|
||||
To run multiple commands in a shell, use::
|
||||
Pour lancer plusieurs commandes dans un shell, utilisez ::
|
||||
|
||||
map f1 launch sh -c "ls && exec zsh"
|
||||
|
||||
To pass the contents of the current screen and scrollback to the started
|
||||
process::
|
||||
Pour passer le contenu de l'écran courant et de l'historique au processus
|
||||
démarré ::
|
||||
|
||||
map f1 launch --stdin-source=@screen_scrollback less
|
||||
|
||||
There are many more powerful options, refer to the complete list below.
|
||||
Il existe beaucoup d'autres options puissantes, référez-vous à la liste complète
|
||||
ci-dessous.
|
||||
|
||||
.. note::
|
||||
To avoid duplicating launch actions with frequently used parameters, you can
|
||||
use :opt:`action_alias` to define launch action aliases. For example::
|
||||
Pour éviter de dupliquer les actions launch avec des paramètres fréquemment
|
||||
utilisés, vous pouvez utiliser :opt:`action_alias` pour définir des alias
|
||||
d'action launch. Par exemple ::
|
||||
|
||||
action_alias launch_tab launch --cwd=current --type=tab
|
||||
map f1 launch_tab vim
|
||||
map f2 launch_tab emacs
|
||||
|
||||
The :kbd:`F1` key will now open :program:`vim` in a new tab with the current
|
||||
windows working directory.
|
||||
La touche :kbd:`F1` ouvrira désormais :program:`vim` dans un nouvel onglet
|
||||
avec le répertoire de travail de la fenêtre courante.
|
||||
|
||||
|
||||
The piping environment
|
||||
L'environnement du pipe
|
||||
--------------------------
|
||||
|
||||
When using :option:`launch --stdin-source`, the program to which the data is
|
||||
piped has a special environment variable declared, :envvar:`KITTY_PIPE_DATA`
|
||||
whose contents are::
|
||||
Lorsque vous utilisez :option:`launch --stdin-source`, le programme auquel les
|
||||
données sont envoyées dispose d'une variable d'environnement spéciale,
|
||||
:envvar:`KITTY_PIPE_DATA`, dont le contenu est ::
|
||||
|
||||
KITTY_PIPE_DATA={scrolled_by}:{cursor_x},{cursor_y}:{lines},{columns}
|
||||
|
||||
where ``scrolled_by`` is the number of lines kitty is currently scrolled by,
|
||||
``cursor_(x|y)`` is the position of the cursor on the screen with ``(1,1)``
|
||||
being the top left corner and ``{lines},{columns}`` being the number of rows
|
||||
and columns of the screen.
|
||||
où ``scrolled_by`` est le nombre de lignes de défilement actuel de kitty,
|
||||
``cursor_(x|y)`` est la position du curseur à l'écran avec ``(1,1)``
|
||||
correspondant au coin supérieur gauche et ``{lines},{columns}`` étant le nombre
|
||||
de lignes et de colonnes de l'écran.
|
||||
|
||||
|
||||
Special arguments
|
||||
Arguments spéciaux
|
||||
-------------------
|
||||
|
||||
There are a few special placeholder arguments that can be specified as part of
|
||||
the command line:
|
||||
Quelques arguments de remplacement spéciaux peuvent être indiqués dans la ligne
|
||||
de commande :
|
||||
|
||||
|
||||
``@selection``
|
||||
Replaced by the currently selected text.
|
||||
Remplacé par le texte actuellement sélectionné.
|
||||
|
||||
``@active-kitty-window-id``
|
||||
Replaced by the id of the currently active kitty window.
|
||||
Remplacé par l'identifiant de la fenêtre kitty actuellement active.
|
||||
|
||||
``@line-count``
|
||||
Replaced by the number of lines in STDIN. Only present when passing some
|
||||
data to STDIN.
|
||||
Remplacé par le nombre de lignes sur STDIN. Présent uniquement lorsque des
|
||||
données sont passées sur STDIN.
|
||||
|
||||
``@input-line-number``
|
||||
Replaced by the number of lines a pager should scroll to match the current
|
||||
scroll position in kitty. See :opt:`scrollback_pager` for details.
|
||||
Remplacé par le nombre de lignes que le pager doit faire défiler pour
|
||||
correspondre à la position de défilement courante dans kitty. Voir
|
||||
:opt:`scrollback_pager` pour les détails.
|
||||
|
||||
``@scrolled-by``
|
||||
Replaced by the number of lines kitty is currently scrolled by.
|
||||
Remplacé par le nombre de lignes de défilement actuel de kitty.
|
||||
|
||||
``@cursor-x``
|
||||
Replaced by the current cursor x position with 1 being the leftmost cell.
|
||||
Remplacé par la position x courante du curseur, 1 étant la cellule la plus
|
||||
à gauche.
|
||||
|
||||
``@cursor-y``
|
||||
Replaced by the current cursor y position with 1 being the topmost cell.
|
||||
Remplacé par la position y courante du curseur, 1 étant la cellule la plus
|
||||
haute.
|
||||
|
||||
``@first-line-on-screen``
|
||||
Replaced by the first line on screen. Can be used for pager positioning.
|
||||
Remplacé par la première ligne à l'écran. Utilisable pour le positionnement
|
||||
du pager.
|
||||
|
||||
``@last-line-on-screen``
|
||||
Replaced by the last line on screen. Can be used for pager positioning.
|
||||
Remplacé par la dernière ligne à l'écran. Utilisable pour le positionnement
|
||||
du pager.
|
||||
|
||||
|
||||
For example::
|
||||
Par exemple ::
|
||||
|
||||
map f1 launch my-program @active-kitty-window-id
|
||||
|
||||
|
||||
.. _watchers:
|
||||
|
||||
Watching launched windows
|
||||
---------------------------
|
||||
Surveiller les fenêtres lancées
|
||||
-------------------------------
|
||||
|
||||
The :option:`launch --watcher` option allows you to specify Python functions
|
||||
that will be called at specific events, such as when the window is resized or
|
||||
closed. Note that you can also specify watchers that are loaded for all windows,
|
||||
via :opt:`watcher`. To create a watcher, specify the path to a Python module
|
||||
that specifies callback functions for the events you are interested in, for
|
||||
create :file:`~/.config/kitty/mywatcher.py` and use :option:`launch --watcher` = :file:`mywatcher.py`:
|
||||
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
|
||||
fermeture de la fenêtre. Notez que vous pouvez aussi indiquer des watchers
|
||||
chargés pour toutes les fenêtres, via :opt:`watcher`. Pour créer un watcher,
|
||||
indiquez le chemin d'un module Python qui définit des fonctions de rappel pour
|
||||
les événements qui vous intéressent ; par exemple créez
|
||||
:file:`~/.config/kitty/mywatcher.py` et utilisez :option:`launch --watcher` =
|
||||
:file:`mywatcher.py` :
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
@@ -134,110 +145,113 @@ create :file:`~/.config/kitty/mywatcher.py` and use :option:`launch --watcher` =
|
||||
|
||||
|
||||
def on_load(boss: Boss, data: dict[str, Any]) -> None:
|
||||
# This is a special function that is called just once when this watcher
|
||||
# module is first loaded, can be used to perform any initialization/one
|
||||
# time setup. Any exceptions in this function are printed to kitty's
|
||||
# STDERR but otherwise ignored.
|
||||
# Fonction spéciale appelée une seule fois lors du premier chargement de
|
||||
# ce module watcher ; utile pour toute initialisation ou configuration
|
||||
# ponctuelle. Les exceptions levées ici sont affichées sur STDERR de
|
||||
# kitty mais ignorées par ailleurs.
|
||||
...
|
||||
|
||||
def on_resize(boss: Boss, window: Window, data: dict[str, Any]) -> None:
|
||||
# Here data will contain old_geometry and new_geometry
|
||||
# Note that resize is also called the first time a window is created
|
||||
# which can be detected as old_geometry will have all zero values, in
|
||||
# particular, old_geometry.xnum and old_geometry.ynum will be zero.
|
||||
# Ici data contient old_geometry et new_geometry.
|
||||
# Notez que resize est aussi appelé lors de la première création d'une
|
||||
# fenêtre, ce qui se détecte au fait que old_geometry aura toutes ses
|
||||
# valeurs à zéro, en particulier old_geometry.xnum et old_geometry.ynum
|
||||
# valant zéro.
|
||||
...
|
||||
|
||||
def on_focus_change(boss: Boss, window: Window, data: dict[str, Any])-> None:
|
||||
# Here data will contain focused
|
||||
# Ici data contient focused
|
||||
...
|
||||
|
||||
def on_close(boss: Boss, window: Window, data: dict[str, Any])-> None:
|
||||
# called when window is closed, typically when the program running in
|
||||
# it exits
|
||||
# appelé lorsque la fenêtre est fermée, typiquement quand le programme
|
||||
# qui y tourne se termine
|
||||
...
|
||||
|
||||
def on_set_user_var(boss: Boss, window: Window, data: dict[str, Any]) -> None:
|
||||
# called when a "user variable" is set or deleted on a window. Here
|
||||
# data will contain key and value
|
||||
# appelé lorsqu'une « variable utilisateur » est définie ou supprimée sur
|
||||
# une fenêtre. Ici data contient key et value
|
||||
...
|
||||
|
||||
def on_title_change(boss: Boss, window: Window, data: dict[str, Any]) -> None:
|
||||
# called when the window title is changed on a window. Here
|
||||
# data will contain title and from_child. from_child will be True
|
||||
# when a title change was requested via escape code from the program
|
||||
# running in the terminal
|
||||
# appelé lorsque le titre d'une fenêtre change. Ici data contient title
|
||||
# et from_child. from_child vaut True lorsque le changement de titre a été
|
||||
# demandé par un code d'échappement du programme qui tourne dans le
|
||||
# terminal
|
||||
...
|
||||
|
||||
def on_cmd_startstop(boss: Boss, window: Window, data: dict[str, Any]) -> None:
|
||||
# called when the shell starts/stops executing a command. Here
|
||||
# data will contain is_start, cmdline and time.
|
||||
# appelé lorsque le shell commence ou termine l'exécution d'une commande.
|
||||
# Ici data contient is_start, cmdline et time.
|
||||
...
|
||||
|
||||
def on_program_status_change(boss: Boss, window: Window, data: dict[str, Any]) -> None:
|
||||
# called when the program status (OSC 7501) records of the window
|
||||
# change. Here data will contain program_status, the list of current
|
||||
# records, each a dict with keys: id, state, kind, progress, app,
|
||||
# title and msg.
|
||||
# appelé lorsque les enregistrements d'état de programme (OSC 7501) de la
|
||||
# fenêtre changent. Ici data contient program_status, la liste des
|
||||
# enregistrements courants, chacun étant un dict avec les clés : id,
|
||||
# state, kind, progress, app, title et msg.
|
||||
...
|
||||
|
||||
def on_color_scheme_preference_change(boss: Boss, window: Window, data: dict[str, Any]) -> None:
|
||||
# called when the color scheme preference of this window changes from
|
||||
# light to dark or vice versa. data contains is_dark and via_escape_code
|
||||
# the latter will be true if the color scheme was changed via escape
|
||||
# code received from the program running in the window
|
||||
# appelé lorsque la préférence de jeu de couleurs de cette fenêtre passe
|
||||
# de clair à sombre ou inversement. data contient is_dark et
|
||||
# via_escape_code, ce dernier valant True si le jeu de couleurs a été
|
||||
# changé par un code d'échappement reçu du programme de la fenêtre
|
||||
...
|
||||
|
||||
def on_tab_bar_dirty(boss: Boss, window: Window, data: dict[str, Any]) -> None:
|
||||
# called when any changes happen to the tab bar, such a new tabs being
|
||||
# created, tab titles changing, tabs moving, etc. Useful to display the
|
||||
# tab bar externally to kitty. This is called even if the tab bar is
|
||||
# hidden. Note that this is called only in *global watchers*, that is
|
||||
# watchers defined in kitty.conf or using the --watcher command line
|
||||
# flag. data contains tab_manager which is the object responsible for
|
||||
# managing all tabs in a single OS Window.
|
||||
# appelé lorsque la barre d'onglets change : création d'onglets, changement
|
||||
# de titre, déplacement d'onglets, etc. Utile pour afficher la barre
|
||||
# d'onglets en dehors de kitty. Appelé même si la barre d'onglets est
|
||||
# masquée. Notez que cela n'est appelé que dans les *watchers globaux*,
|
||||
# c'est-à-dire les watchers définis dans kitty.conf ou avec l'option
|
||||
# --watcher. data contient tab_manager, l'objet responsable de la gestion
|
||||
# de tous les onglets d'une même fenêtre OS.
|
||||
...
|
||||
|
||||
def on_quit(boss: Boss, window: Window, data: dict[str, Any]) -> None:
|
||||
# called when kitty is about to quit. This is called in *global watchers*
|
||||
# only. It is called twice: once before the quit confirmation dialog is
|
||||
# shown (data['confirmed'] will be False) and once after the user has
|
||||
# confirmed quitting (data['confirmed'] will be True). Setting
|
||||
# data['aborted'] to True will abort the quit in both cases.
|
||||
# appelé lorsque kitty est sur le point de quitter. Appelé uniquement dans
|
||||
# les *watchers globaux*. Appelé deux fois : une fois avant l'affichage de
|
||||
# la boîte de confirmation (data['confirmed'] vaut False) et une fois
|
||||
# après confirmation par l'utilisateur (data['confirmed'] vaut True).
|
||||
# Mettre data['aborted'] à True annule la fermeture dans les deux cas.
|
||||
...
|
||||
|
||||
|
||||
Every callback is passed a reference to the global ``Boss`` object as well as
|
||||
the ``Window`` object the action is occurring on. The ``data`` object is a dict
|
||||
that contains event dependent data. You have full access to kitty internals in
|
||||
the watcher scripts, however kitty internals are not documented/stable so for
|
||||
most things you are better off using the kitty :doc:`Remote control API </remote-control>`.
|
||||
Simply call :code:`boss.call_remote_control()`, with the same arguments you
|
||||
would pass to ``kitten @``. For example:
|
||||
Chaque fonction de rappel reçoit une référence à l'objet global ``Boss`` ainsi
|
||||
qu'à l'objet ``Window`` concerné par l'action. L'objet ``data`` est un dict qui
|
||||
contient les données propres à l'événement. Vous avez un accès complet aux
|
||||
entrailles de kitty dans les scripts watcher, mais elles ne sont ni
|
||||
documentées ni stables ; pour la plupart des besoins, mieux vaut utiliser
|
||||
l':doc:`API de contrôle à distance </remote-control>` de kitty. Appelez
|
||||
simplement :code:`boss.call_remote_control()`, avec les mêmes arguments que
|
||||
vous passeriez à ``kitten @``. Par exemple :
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
def on_resize(boss: Boss, window: Window, data: dict[str, Any]) -> None:
|
||||
# send some text to the resized window
|
||||
# envoie du texte à la fenêtre redimensionnée
|
||||
boss.call_remote_control(window, ('send-text', f'--match=id:{window.id}', 'hello world'))
|
||||
|
||||
Run, ``kitten @ --help`` in a kitty terminal, to see all the remote control
|
||||
commands available to you.
|
||||
Lancez ``kitten @ --help`` dans un terminal kitty pour voir toutes les commandes
|
||||
de contrôle à distance à votre disposition.
|
||||
|
||||
|
||||
Finding executables
|
||||
-----------------------
|
||||
Recherche des exécutables
|
||||
-------------------------
|
||||
|
||||
When you specify a command to run as just a name rather than an absolute path,
|
||||
it is searched for in the system-wide :envvar:`PATH` environment variable. Note
|
||||
that this **may not** be the value of :envvar:`PATH` inside a shell, as shell
|
||||
startup scripts often change the value of this variable. If it is not found
|
||||
there, then a system specific list of default paths is searched. If it is still
|
||||
not found, then your shell is run and the value of :envvar:`PATH` inside the
|
||||
shell is used.
|
||||
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
|
||||
:envvar:`PATH` du système. Notez que ce **n'est peut-être pas** la valeur de
|
||||
:envvar:`PATH` dans un shell, car les scripts de démarrage du shell modifient
|
||||
souvent cette variable. Si la commande n'y est pas trouvée, une liste de
|
||||
chemins par défaut propre au système est parcourue. Si elle n'est toujours pas
|
||||
trouvée, votre shell est lancé et la valeur de :envvar:`PATH` à l'intérieur du
|
||||
shell est utilisée.
|
||||
|
||||
See :opt:`exe_search_path` for details and how to control this.
|
||||
Voir :opt:`exe_search_path` pour les détails et la façon de contrôler cela.
|
||||
|
||||
Syntax reference
|
||||
------------------
|
||||
Référence de syntaxe
|
||||
--------------------
|
||||
|
||||
.. include:: /generated/launch.rst
|
||||
@@ -428,11 +428,61 @@ below::
|
||||
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
|
||||
------------------------
|
||||
|
||||
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
|
||||
------------------------------
|
||||
|
||||
|
||||
+64
-59
@@ -1,36 +1,38 @@
|
||||
Mark text on screen
|
||||
---------------------
|
||||
Marquer du texte à l'écran
|
||||
--------------------------
|
||||
|
||||
|
||||
kitty has the ability to mark text on the screen based on regular expressions.
|
||||
This can be useful to highlight words or phrases when browsing output from long
|
||||
running programs or similar. Lets start with a few examples:
|
||||
kitty peut marquer du texte à l'écran à partir d'expressions régulières. C'est
|
||||
utile pour mettre en évidence des mots ou des phrases lors de la lecture de la
|
||||
sortie de programmes longs. Commençons par quelques exemples :
|
||||
|
||||
Examples
|
||||
Exemples
|
||||
----------
|
||||
|
||||
Suppose we want to be able to highlight the word :code:`ERROR` in the current
|
||||
window. Add the following to :file:`kitty.conf`::
|
||||
Supposons que nous voulions pouvoir mettre en évidence le mot :code:`ERROR`
|
||||
dans la fenêtre courante. Ajoutez ce qui suit à :file:`kitty.conf` ::
|
||||
|
||||
map f1 toggle_marker text 1 ERROR
|
||||
|
||||
Now when you press :kbd:`F1`, all instances of the word :code:`ERROR` will be
|
||||
highlighted. To turn off the highlighting, press :kbd:`F1` again.
|
||||
If you want to make it case-insensitive, use::
|
||||
Désormais, quand vous appuyez sur :kbd:`F1`, toutes les occurrences du mot
|
||||
:code:`ERROR` sont mises en évidence. Pour désactiver la mise en évidence,
|
||||
appuyez à nouveau sur :kbd:`F1`. Si vous voulez la rendre insensible à la
|
||||
casse, utilisez ::
|
||||
|
||||
map f1 toggle_marker itext 1 ERROR
|
||||
|
||||
To make it match only complete words, use::
|
||||
Pour qu'elle ne corresponde qu'à des mots complets, utilisez ::
|
||||
|
||||
map f1 toggle_marker regex 1 \\bERROR\\b
|
||||
|
||||
Suppose you want to highlight both :code:`ERROR` and :code:`WARNING`, case
|
||||
insensitively::
|
||||
Supposons que vous vouliez mettre en évidence à la fois :code:`ERROR` et
|
||||
:code:`WARNING`, sans tenir compte de la casse ::
|
||||
|
||||
map f1 toggle_marker iregex 1 \\bERROR\\b 2 \\bWARNING\\b
|
||||
|
||||
kitty supports up to 3 mark groups (the numbers in the commands above). You
|
||||
can control the colors used for these groups in :file:`kitty.conf` with::
|
||||
kitty prend en charge jusqu'à 3 groupes de marques (les nombres dans les
|
||||
commandes ci-dessus). Vous pouvez contrôler les couleurs utilisées pour ces
|
||||
groupes dans :file:`kitty.conf` avec ::
|
||||
|
||||
mark1_foreground red
|
||||
mark1_background gray
|
||||
@@ -39,89 +41,92 @@ can control the colors used for these groups in :file:`kitty.conf` with::
|
||||
|
||||
|
||||
.. note::
|
||||
For performance reasons, matching is done per line only, and only when that
|
||||
line is altered in any way. So you cannot match text that stretches across
|
||||
multiple lines.
|
||||
Pour des raisons de performance, la correspondance se fait ligne par ligne
|
||||
uniquement, et seulement lorsqu'une ligne est modifiée d'une manière ou
|
||||
d'une autre. Vous ne pouvez donc pas faire correspondre du texte réparti sur
|
||||
plusieurs lignes.
|
||||
|
||||
|
||||
Creating markers dynamically
|
||||
Créer des marqueurs dynamiquement
|
||||
---------------------------------
|
||||
|
||||
If you want to create markers dynamically rather than pre-defining them in
|
||||
:file:`kitty.conf`, you can do so as follows::
|
||||
Si vous voulez créer des marqueurs dynamiquement plutôt que de les prédéfinir
|
||||
dans :file:`kitty.conf`, vous pouvez le faire ainsi ::
|
||||
|
||||
map f1 create_marker
|
||||
map f2 remove_marker
|
||||
|
||||
Then pressing :kbd:`F1` will allow you to enter the marker definition and set it
|
||||
and pressing :kbd:`F2` will remove the marker. :ac:`create_marker` accepts the
|
||||
same syntax as :ac:`toggle_marker` above. Note that while creating markers, the
|
||||
prompt has history so you can easily re-use previous marker expressions.
|
||||
Appuyer sur :kbd:`F1` vous permettra alors de saisir la définition du marqueur
|
||||
et de la définir, et appuyer sur :kbd:`F2` supprimera le marqueur.
|
||||
:ac:`create_marker` accepte la même syntaxe que :ac:`toggle_marker` ci-dessus.
|
||||
Notez que lors de la création de marqueurs, l'invite dispose d'un historique,
|
||||
vous pouvez donc facilement réutiliser des expressions de marqueur précédentes.
|
||||
|
||||
You can also use the facilities for :doc:`remote-control` to dynamically add or
|
||||
remove markers.
|
||||
Vous pouvez aussi utiliser les facilités de :doc:`contrôle à distance
|
||||
<remote-control>` pour ajouter ou supprimer des marqueurs dynamiquement.
|
||||
|
||||
|
||||
Scrolling to marks
|
||||
--------------------
|
||||
Défiler jusqu'aux marques
|
||||
-------------------------
|
||||
|
||||
kitty has a :ac:`scroll_to_mark` action to scroll to the next line that contains
|
||||
a mark. You can use it by mapping it to some shortcut in :file:`kitty.conf`::
|
||||
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
|
||||
raccourci dans :file:`kitty.conf` ::
|
||||
|
||||
map ctrl+p scroll_to_mark prev
|
||||
map ctrl+n scroll_to_mark next
|
||||
|
||||
Then pressing :kbd:`Ctrl+P` will scroll to the first line in the scrollback
|
||||
buffer above the current top line that contains a mark. Pressing :kbd:`Ctrl+N`
|
||||
will scroll to show the first line below the current last line that contains
|
||||
a mark. If you wish to jump to a mark of a specific type, you can add that to
|
||||
the mapping::
|
||||
Appuyer sur :kbd:`Ctrl+P` défilera alors jusqu'à la première ligne du tampon
|
||||
d'historique, au-dessus de la ligne du haut actuelle, contenant une marque.
|
||||
Appuyer sur :kbd:`Ctrl+N` défilera pour afficher la première ligne en dessous de
|
||||
la ligne du bas actuelle contenant une marque. Si vous souhaitez sauter à une
|
||||
marque d'un type particulier, vous pouvez l'ajouter à l'association ::
|
||||
|
||||
map ctrl+1 scroll_to_mark prev 1
|
||||
|
||||
Which will scroll only to marks of type 1.
|
||||
Ce qui ne défilera que vers les marques de type 1.
|
||||
|
||||
|
||||
The full syntax for creating marks
|
||||
-------------------------------------
|
||||
La syntaxe complète pour créer des marques
|
||||
------------------------------------------
|
||||
|
||||
The syntax of the :ac:`toggle_marker` action is::
|
||||
La syntaxe de l'action :ac:`toggle_marker` est ::
|
||||
|
||||
toggle_marker <marker-type> <specification>
|
||||
|
||||
Here :code:`marker-type` is one of:
|
||||
Ici :code:`marker-type` vaut l'un des suivants :
|
||||
|
||||
* :code:`text` - Simple substring matching
|
||||
* :code:`itext` - Case-insensitive substring matching
|
||||
* :code:`regex` - A Python regular expression
|
||||
* :code:`iregex` - A case-insensitive Python regular expression
|
||||
* :code:`function` - An arbitrary function defined in a Python file, see :ref:`marker_funcs`.
|
||||
* :code:`text` - Correspondance simple de sous-chaîne
|
||||
* :code:`itext` - Correspondance de sous-chaîne insensible à la casse
|
||||
* :code:`regex` - Une expression régulière Python
|
||||
* :code:`iregex` - Une expression régulière Python insensible à la casse
|
||||
* :code:`function` - Une fonction arbitraire définie dans un fichier Python, voir :ref:`marker_funcs`.
|
||||
|
||||
.. _marker_funcs:
|
||||
|
||||
Arbitrary marker functions
|
||||
-----------------------------
|
||||
Fonctions de marqueur arbitraires
|
||||
---------------------------------
|
||||
|
||||
You can create your own marker functions. Create a Python file named
|
||||
:file:`mymarker.py` and in it create a :code:`marker` function. This function
|
||||
receives the text of the line as input and must yield three numbers,
|
||||
the starting character position, the ending character position and the mark
|
||||
group (1-3). For example:
|
||||
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
|
||||
fonction reçoit le texte de la ligne en entrée et doit produire trois nombres :
|
||||
la position du caractère de début, la position du caractère de fin et le groupe
|
||||
de marque (1-3). Par exemple :
|
||||
|
||||
.. code-block::
|
||||
.. code-block:: python
|
||||
|
||||
def marker(text):
|
||||
# Function to highlight the letter X
|
||||
# Fonction pour mettre en évidence la lettre X
|
||||
for i, ch in enumerate(text):
|
||||
if ch.lower() == 'x':
|
||||
yield i, i, 3
|
||||
|
||||
|
||||
Save this file somewhere and in :file:`kitty.conf`, use::
|
||||
Enregistrez ce fichier quelque part et, dans :file:`kitty.conf`, utilisez ::
|
||||
|
||||
map f1 toggle_marker function /path/to/mymarker.py
|
||||
|
||||
If you save the file in the :ref:`kitty config directory <confloc>`, you can
|
||||
use::
|
||||
Si vous enregistrez le fichier dans le :ref:`dossier de configuration de kitty
|
||||
<confloc>`, vous pouvez utiliser ::
|
||||
|
||||
map f1 toggle_marker function mymarker.py
|
||||
+98
-86
@@ -1,170 +1,182 @@
|
||||
Scripting the mouse click
|
||||
Script du clic de souris
|
||||
======================================================
|
||||
|
||||
|kitty| has support for :term:`terminal hyperlinks <hyperlinks>`. These are
|
||||
generated by many terminal programs, such as ``ls``, ``gcc``, ``systemd``,
|
||||
:ref:`tool_mcat`, etc. You can customize exactly what happens when clicking on
|
||||
these hyperlinks in |kitty|.
|
||||
|kitty| prend en charge les :term:`liens hypertextes du terminal <hyperlinks>`.
|
||||
Ils sont générés par de nombreux programmes de terminal, comme ``ls``, ``gcc``,
|
||||
``systemd``, :ref:`tool_mcat`, etc. Vous pouvez personnaliser exactement ce qui
|
||||
se passe lorsque vous cliquez sur ces liens dans |kitty|.
|
||||
|
||||
You can tell kitty to take arbitrarily many, complex actions when a link is
|
||||
clicked. Let us illustrate with some examples, first. Create the file
|
||||
:file:`~/.config/kitty/open-actions.conf` with the following:
|
||||
Vous pouvez demander à kitty d'effectuer autant d'actions complexes que vous
|
||||
voulez lors d'un clic sur un lien. Illustrons d'abord avec quelques exemples.
|
||||
Créez le fichier :file:`~/.config/kitty/open-actions.conf` avec ceci :
|
||||
|
||||
.. code:: conf
|
||||
|
||||
# Open any image in the full kitty window by clicking on it
|
||||
# Ouvre toute image dans la fenêtre kitty complète en cliquant dessus
|
||||
protocol file
|
||||
mime image/*
|
||||
action launch --type=overlay kitten icat --hold -- ${FILE_PATH}
|
||||
|
||||
Now, run ``ls --hyperlink=auto`` in kitty and click on the filename of an
|
||||
image, holding down :kbd:`ctrl+shift`. It will be opened over the current
|
||||
window. Press any key to close it.
|
||||
Lancez maintenant ``ls --hyperlink=auto`` dans kitty et cliquez sur le nom de
|
||||
fichier d'une image en maintenant :kbd:`ctrl+shift`. Elle s'ouvrira par-dessus
|
||||
la fenêtre courante. Appuyez sur n'importe quelle touche pour la fermer.
|
||||
|
||||
.. note::
|
||||
|
||||
The :program:`ls` comes with macOS does not support hyperlink, you need to
|
||||
install `GNU Coreutils <https://www.gnu.org/software/coreutils/>`__. If you
|
||||
install it via `Homebrew <https://formulae.brew.sh/formula/coreutils>`__, it
|
||||
will be :program:`gls`.
|
||||
Le :program:`ls` fourni avec macOS ne prend pas en charge les liens
|
||||
hypertextes, vous devez installer `GNU Coreutils
|
||||
<https://www.gnu.org/software/coreutils/>`__. Si vous l'installez via
|
||||
`Homebrew <https://formulae.brew.sh/formula/coreutils>`__, ce sera
|
||||
:program:`gls`.
|
||||
|
||||
Each entry in :file:`open-actions.conf` consists of one or more
|
||||
:ref:`matching_criteria`, such as ``protocol`` and ``mime`` and one or more
|
||||
``action`` entries. In the example above kitty uses the :doc:`launch <launch>`
|
||||
action which can be used to run external programs. Entries are separated by
|
||||
blank lines.
|
||||
Chaque entrée de :file:`open-actions.conf` se compose d'un ou plusieurs
|
||||
:ref:`critères de correspondance <matching_criteria>`, comme ``protocol`` et
|
||||
``mime``, et d'une ou plusieurs entrées ``action``. Dans l'exemple ci-dessus,
|
||||
kitty utilise l'action :doc:`launch <launch>` qui sert à lancer des programmes
|
||||
externes. Les entrées sont séparées par des lignes vides.
|
||||
|
||||
Actions are very powerful, anything that you can map to a key combination in
|
||||
:file:`kitty.conf` can be used as an action. You can specify more than one
|
||||
action per entry if you like, for example:
|
||||
Les actions sont très puissantes : tout ce que vous pouvez associer à une
|
||||
combinaison de touches dans :file:`kitty.conf` peut servir d'action. Vous pouvez
|
||||
indiquer plusieurs actions par entrée si vous le souhaitez, par exemple :
|
||||
|
||||
|
||||
.. code:: conf
|
||||
|
||||
# Tail a log file (*.log) in a new OS Window and reduce its font size
|
||||
# Suit un fichier de log (*.log) dans une nouvelle fenêtre OS et réduit sa taille de police
|
||||
protocol file
|
||||
ext log
|
||||
action launch --title ${FILE} --type=os-window tail -f -- ${FILE_PATH}
|
||||
action change_font_size current -2
|
||||
|
||||
|
||||
In the launch specification you can expand environment variables, as shown in
|
||||
the examples above. In addition to regular environment variables, there are
|
||||
some special variables, documented below:
|
||||
Dans la spécification launch, vous pouvez développer les variables
|
||||
d'environnement, comme montré dans les exemples ci-dessus. En plus des variables
|
||||
d'environnement habituelles, quelques variables spéciales existent, documentées
|
||||
ci-dessous :
|
||||
|
||||
``URL``
|
||||
The full URL being opened
|
||||
L'URL complète ouverte
|
||||
|
||||
``FILE_PATH``
|
||||
The path portion of the URL (unquoted)
|
||||
La partie chemin de l'URL (sans guillemets)
|
||||
|
||||
``FILE``
|
||||
The file portion of the path of the URL (unquoted)
|
||||
La partie fichier du chemin de l'URL (sans guillemets)
|
||||
|
||||
``FRAGMENT``
|
||||
The fragment (unquoted), if any of the URL or the empty string.
|
||||
Le fragment (sans guillemets), s'il existe dans l'URL, ou la chaîne vide.
|
||||
|
||||
``NETLOC``
|
||||
The net location aka hostname (unquoted), if any of the URL or the empty string.
|
||||
L'emplacement réseau, c'est-à-dire le nom d'hôte (sans guillemets), s'il
|
||||
existe dans l'URL, ou la chaîne vide.
|
||||
|
||||
``URL_PATH``
|
||||
The path, query and fragment portions of the URL, without any
|
||||
unquoting.
|
||||
Les parties chemin, requête et fragment de l'URL, sans aucun
|
||||
désséchappement.
|
||||
|
||||
``EDITOR``
|
||||
The terminal based text editor. The configured :opt:`editor` in
|
||||
:file:`kitty.conf` is preferred.
|
||||
L'éditeur de texte en mode terminal. L'option :opt:`editor` configurée dans
|
||||
:file:`kitty.conf` est préférée.
|
||||
|
||||
``SHELL``
|
||||
The path to the shell. The configured :opt:`shell` in :file:`kitty.conf` is
|
||||
preferred, without arguments.
|
||||
Le chemin du shell. L'option :opt:`shell` configurée dans
|
||||
:file:`kitty.conf` est préférée, sans arguments.
|
||||
|
||||
.. note::
|
||||
You can use the :opt:`action_alias` option just as in :file:`kitty.conf` to
|
||||
define aliases for frequently used actions.
|
||||
Vous pouvez utiliser l'option :opt:`action_alias` comme dans
|
||||
:file:`kitty.conf` pour définir des alias d'actions fréquemment utilisées.
|
||||
|
||||
|
||||
.. _matching_criteria:
|
||||
|
||||
Matching criteria
|
||||
------------------
|
||||
Critères de correspondance
|
||||
--------------------------
|
||||
|
||||
An entry in :file:`open-actions.conf` must have one or more matching criteria.
|
||||
URLs that match all criteria for an entry will trigger that entry's actions.
|
||||
Processing stops at the first matching entry, so put more specific matching
|
||||
criteria at the start of the list. Entries in the file are separated by blank
|
||||
lines. The various available criteria are:
|
||||
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
|
||||
les actions de cette entrée. Le traitement s'arrête à la première entrée
|
||||
correspondante, placez donc les critères les plus spécifiques au début de la
|
||||
liste. Les entrées du fichier sont séparées par des lignes vides. Les différents
|
||||
critères disponibles sont :
|
||||
|
||||
``protocol``
|
||||
A comma separated list of protocols, for example: ``http, https``. If
|
||||
absent, there is no constraint on protocol.
|
||||
Une liste de protocoles séparés par des virgules, par exemple : ``http,
|
||||
https``. En son absence, il n'y a aucune contrainte de protocole.
|
||||
|
||||
``url``
|
||||
A regular expression that must match against the entire (unquoted) URL
|
||||
Une expression régulière qui doit correspondre à l'URL (sans guillemets)
|
||||
entière
|
||||
|
||||
``fragment_matches``
|
||||
A regular expression that must match against the fragment (part after #) in
|
||||
the URL
|
||||
Une expression régulière qui doit correspondre au fragment (la partie après
|
||||
#) de l'URL
|
||||
|
||||
``mime``
|
||||
A comma separated list of MIME types, for example: ``text/*, image/*,
|
||||
application/pdf``. You can add MIME types to kitty by creating a file named
|
||||
:file:`mime.types` in the :ref:`kitty configuration directory <confloc>`.
|
||||
Useful if your system MIME database does not have definitions you need. This
|
||||
file is in the standard format of one definition per line, like:
|
||||
``text/plain rst md``. Note that the MIME type for directories is
|
||||
``inode/directory``. MIME types are detected based on file name, not
|
||||
file contents. On Linux and BSD the system shared-mime-info database
|
||||
(:file:`mime/mime.cache` in the XDG data directories) is used.
|
||||
Une liste de types MIME séparés par des virgules, par exemple : ``text/*,
|
||||
image/*, application/pdf``. Vous pouvez ajouter des types MIME à kitty en
|
||||
créant un fichier nommé :file:`mime.types` dans le :ref:`dossier de
|
||||
configuration de kitty <confloc>`. Utile si la base MIME de votre système
|
||||
n'a pas les définitions dont vous avez besoin. Ce fichier utilise le format
|
||||
standard, à raison d'une définition par ligne, comme :
|
||||
``text/plain rst md``. Notez que le type MIME des dossiers est
|
||||
``inode/directory``. Les types MIME sont détectés d'après le nom du fichier,
|
||||
pas d'après son contenu. Sous Linux et BSD, la base partagée
|
||||
shared-mime-info du système (:file:`mime/mime.cache` dans les dossiers de
|
||||
données XDG) est utilisée.
|
||||
|
||||
``ext``
|
||||
A comma separated list of file extensions, for example: ``jpeg, tar.gz``
|
||||
Une liste d'extensions de fichiers séparées par des virgules, par exemple :
|
||||
``jpeg, tar.gz``
|
||||
|
||||
``file``
|
||||
A shell glob pattern that must match the filename, for example:
|
||||
``image-??.png``
|
||||
Un motif glob du shell qui doit correspondre au nom du fichier, par
|
||||
exemple : ``image-??.png``
|
||||
|
||||
``path``
|
||||
A shell glob pattern that must match the entire unquoted URL path, for
|
||||
example: ``/home/*/projects/*.py``. Both ``file`` and ``path`` matching
|
||||
ignore case.
|
||||
Un motif glob du shell qui doit correspondre au chemin complet de l'URL sans
|
||||
guillemets, par exemple : ``/home/*/projects/*.py``. Les correspondances
|
||||
``file`` et ``path`` ignorent la casse.
|
||||
|
||||
|
||||
.. _launch_actions:
|
||||
|
||||
Scripting the opening of files with kitty
|
||||
Script de l'ouverture de fichiers avec kitty
|
||||
-------------------------------------------------------
|
||||
|
||||
On macOS you can use :guilabel:`Open With` in Finder or drag and drop files and
|
||||
URLs onto the kitty dock icon to open them with kitty. Similarly on Linux, you
|
||||
can associate certain files types to open in kitty. The default actions are:
|
||||
Sous macOS, vous pouvez utiliser :guilabel:`Ouvrir avec` dans le Finder ou
|
||||
glisser-déposer des fichiers et des URL sur l'icône du dock de kitty pour les
|
||||
ouvrir avec kitty. De même sous Linux, vous pouvez associer certains types de
|
||||
fichiers à ouvrir dans kitty. Les actions par défaut sont :
|
||||
|
||||
* Open text files in your editor and images using the icat kitten.
|
||||
* Run shell scripts in a shell
|
||||
* Open SSH urls using the ssh command
|
||||
* Ouvrir les fichiers texte dans votre éditeur et les images avec le kitten icat.
|
||||
* Lancer les scripts shell dans un shell
|
||||
* Ouvrir les URL SSH avec la commande ssh
|
||||
|
||||
These actions can also be executed from the command line by running::
|
||||
Ces actions peuvent aussi être exécutées depuis la ligne de commande en
|
||||
lançant ::
|
||||
|
||||
kitty +open file_or_url another_url ...
|
||||
|
||||
# macOS only
|
||||
# macOS uniquement
|
||||
open -a kitty.app file_or_url another_url ...
|
||||
|
||||
Since macOS lacks an official interface to set default URL scheme handlers,
|
||||
kitty has a command you can use for it. The first argument for is the URL
|
||||
scheme, and the second optional argument is the bundle id of the app, which
|
||||
defaults to kitty, if not specified. For example:
|
||||
Comme macOS n'offre pas d'interface officielle pour définir les gestionnaires de
|
||||
schémas d'URL par défaut, kitty dispose d'une commande que vous pouvez utiliser
|
||||
pour cela. Le premier argument est le schéma d'URL, et le second argument
|
||||
facultatif est l'identifiant de bundle de l'application, qui vaut kitty par
|
||||
défaut s'il n'est pas indiqué. Par exemple :
|
||||
|
||||
.. code-block:: sh
|
||||
|
||||
# Set kitty as the handler for ssh:// URLs
|
||||
# Définit kitty comme gestionnaire des URL ssh://
|
||||
kitty +runpy 'from kitty.fast_data_types import cocoa_set_url_handler; import sys; cocoa_set_url_handler(*sys.argv[1:]); print("OK")' ssh
|
||||
# Set someapp as the handler for xyz:// URLs
|
||||
# Définit someapp comme gestionnaire des URL xyz://
|
||||
kitty +runpy 'from kitty.fast_data_types import cocoa_set_url_handler; import sys; cocoa_set_url_handler(*sys.argv[1:]); print("OK")' xyz someapp.bundle.identifier
|
||||
|
||||
You can customize these actions by creating a :file:`launch-actions.conf` file
|
||||
in the :ref:`kitty config directory <confloc>`, just like the
|
||||
:file:`open-actions.conf` file above. For example:
|
||||
Vous pouvez personnaliser ces actions en créant un fichier
|
||||
:file:`launch-actions.conf` dans le :ref:`dossier de configuration de kitty
|
||||
<confloc>`, exactement comme le fichier :file:`open-actions.conf` ci-dessus. Par
|
||||
exemple :
|
||||
|
||||
.. literalinclude:: ../kitty/open_actions.py
|
||||
:language: conf
|
||||
|
||||
+213
-178
@@ -1,40 +1,47 @@
|
||||
Overview
|
||||
Vue d'ensemble
|
||||
==============
|
||||
|
||||
Design philosophy
|
||||
-------------------
|
||||
Philosophie de conception
|
||||
-------------------------
|
||||
|
||||
|kitty| is designed for power keyboard users. To that end all its controls work
|
||||
with the keyboard (although it fully supports mouse interactions as well). Its
|
||||
configuration is a simple, human editable, single file for easy reproducibility
|
||||
(I like to store configuration in source control).
|
||||
|kitty| est conçu pour les utilisateurs intensifs du clavier. À cette fin,
|
||||
toutes ses commandes fonctionnent au clavier (bien qu'il prenne aussi
|
||||
pleinement en charge les interactions à la souris). Sa configuration est un
|
||||
fichier unique, simple et modifiable à la main, pour une reproductibilité
|
||||
facile (j'aime stocker la configuration dans un système de contrôle de
|
||||
versions).
|
||||
|
||||
The code in |kitty| is designed to be simple, modular and hackable. It is
|
||||
written in a mix of C (for performance sensitive parts), Python (for easy
|
||||
extensibility and flexibility of the UI) and Go (for the command line
|
||||
:term:`kittens`). It does not depend on any large and complex UI toolkit,
|
||||
using only OpenGL for rendering everything.
|
||||
Le code de |kitty| est conçu pour être simple, modulaire et bricolable. Il est
|
||||
écrit dans un mélange de C (pour les parties sensibles aux performances), de
|
||||
Python (pour l'extensibilité et la souplesse de l'interface) et de Go (pour les
|
||||
:term:`kittens` en ligne de commande). Il ne dépend d'aucune boîte à outils
|
||||
d'interface graphique volumineuse et complexe, et n'utilise qu'OpenGL pour tout
|
||||
dessiner.
|
||||
|
||||
Finally, |kitty| is designed from the ground up to support all modern terminal
|
||||
features, such as Unicode, true color, bold/italic fonts, text formatting, etc.
|
||||
It even extends existing text formatting escape codes, to add support for
|
||||
features not available elsewhere, such as colored and styled (curly) underlines.
|
||||
One of the design goals of |kitty| is to be easily extensible so that new
|
||||
features can be added in the future with relatively little effort.
|
||||
Enfin, |kitty| est conçu depuis le départ pour prendre en charge toutes les
|
||||
fonctionnalités modernes des terminaux, comme Unicode, les couleurs réelles,
|
||||
les polices grasses et italiques, le formatage du texte, etc. Il étend même
|
||||
les codes d'échappement de formatage existants pour ajouter la prise en charge
|
||||
de fonctionnalités indisponibles ailleurs, comme les soulignements colorés et
|
||||
stylés (ondulés). L'un des objectifs de conception de |kitty| est d'être
|
||||
facilement extensible, afin que de nouvelles fonctionnalités puissent être
|
||||
ajoutées à l'avenir avec relativement peu d'effort.
|
||||
|
||||
.. include:: basic.rst
|
||||
|
||||
|
||||
Configuring kitty
|
||||
-------------------
|
||||
Configurer kitty
|
||||
-----------------
|
||||
|
||||
|kitty| is highly configurable, everything from keyboard shortcuts to painting
|
||||
frames-per-second. Press :sc:`edit_config_file` in kitty to open its fully
|
||||
commented sample config file in your text editor. For details see the
|
||||
:doc:`configuration docs <conf>`.
|
||||
|kitty| est extrêmement configurable, des raccourcis clavier jusqu'au nombre
|
||||
d'images par seconde. Appuyez sur :sc:`edit_config_file` dans kitty pour ouvrir
|
||||
son fichier de configuration d'exemple entièrement commenté dans votre éditeur
|
||||
de texte. Pour les détails, voir la :doc:`documentation de configuration
|
||||
<conf>`.
|
||||
|
||||
You can quickly browse all available mappable actions by pressing
|
||||
:sc:`command_palette`, see :doc:`kittens/command-palette` for details.
|
||||
Vous pouvez parcourir rapidement toutes les actions associables disponibles en
|
||||
appuyant sur :sc:`command_palette`, voir :doc:`kittens/command-palette` pour
|
||||
les détails.
|
||||
|
||||
.. toctree::
|
||||
:hidden:
|
||||
@@ -44,70 +51,77 @@ You can quickly browse all available mappable actions by pressing
|
||||
|
||||
.. _layouts:
|
||||
|
||||
Layouts
|
||||
----------
|
||||
Dispositions
|
||||
------------
|
||||
|
||||
A :term:`layout` is an arrangement of multiple :term:`kitty windows <window>`
|
||||
inside a top-level :term:`OS window <os_window>`. The layout manages all its
|
||||
windows automatically, resizing and moving them as needed. You can create a new
|
||||
:term:`window` using the :sc:`new_window` key combination.
|
||||
Une :term:`disposition <layout>` est un agencement de plusieurs
|
||||
:term:`fenêtres kitty <window>` à l'intérieur d'une :term:`fenêtre OS
|
||||
<os_window>` de premier niveau. La disposition gère automatiquement toutes ses
|
||||
fenêtres, en les redimensionnant et en les déplaçant selon les besoins. Vous
|
||||
pouvez créer une nouvelle :term:`fenêtre <window>` avec la combinaison de
|
||||
touches :sc:`new_window`.
|
||||
|
||||
Currently, there are seven layouts available:
|
||||
Actuellement, sept dispositions sont disponibles :
|
||||
|
||||
* **Fat** -- One (or optionally more) windows are shown full width on the top,
|
||||
the rest of the windows are shown side-by-side on the bottom
|
||||
* **Fat** -- Une fenêtre (ou éventuellement plusieurs) est affichée sur toute
|
||||
la largeur en haut, le reste des fenêtres est affiché côte à côte en bas
|
||||
|
||||
* **Grid** -- All windows are shown in a grid
|
||||
* **Grid** -- Toutes les fenêtres sont affichées dans une grille
|
||||
|
||||
* **Horizontal** -- All windows are shown side-by-side
|
||||
* **Horizontal** -- Toutes les fenêtres sont affichées côte à côte
|
||||
|
||||
* **Splits** -- Windows arranged in arbitrary patterns created using horizontal
|
||||
and vertical splits
|
||||
* **Splits** -- Les fenêtres sont agencées selon des motifs arbitraires créés
|
||||
à l'aide de divisions horizontales et verticales
|
||||
|
||||
* **Stack** -- Only a single maximized window is shown at a time
|
||||
* **Stack** -- Une seule fenêtre maximisée est affichée à la fois
|
||||
|
||||
* **Tall** -- One (or optionally more) windows are shown full height on the
|
||||
left, the rest of the windows are shown one below the other on the right
|
||||
* **Tall** -- Une fenêtre (ou éventuellement plusieurs) est affichée sur toute
|
||||
la hauteur à gauche, le reste des fenêtres est affiché l'une sous l'autre à
|
||||
droite
|
||||
|
||||
* **Vertical** -- All windows are shown one below the other
|
||||
* **Vertical** -- Toutes les fenêtres sont affichées l'une sous l'autre
|
||||
|
||||
By default, all layouts are enabled and you can switch between layouts using
|
||||
the :sc:`next_layout` key combination. You can also create shortcuts to select
|
||||
particular layouts, and choose which layouts you want to enable, see
|
||||
:ref:`conf-kitty-shortcuts.layout` for examples. The first layout listed in
|
||||
:opt:`enabled_layouts` becomes the default layout.
|
||||
Par défaut, toutes les dispositions sont activées et vous pouvez passer de
|
||||
l'une à l'autre avec la combinaison de touches :sc:`next_layout`. Vous pouvez
|
||||
aussi créer des raccourcis pour choisir une disposition particulière et
|
||||
sélectionner les dispositions que vous voulez activer, voir
|
||||
:ref:`conf-kitty-shortcuts.layout` pour des exemples. La première disposition
|
||||
listée dans :opt:`enabled_layouts` devient la disposition par défaut.
|
||||
|
||||
For more details on the layouts and how to use them see :doc:`the documentation
|
||||
<layouts>`.
|
||||
Pour plus de détails sur les dispositions et leur utilisation, voir :doc:`la
|
||||
documentation <layouts>`.
|
||||
|
||||
.. toctree::
|
||||
:hidden:
|
||||
|
||||
layouts
|
||||
|
||||
Extending kitty
|
||||
Étendre kitty
|
||||
------------------
|
||||
|
||||
kitty has a powerful framework for scripting. You can create small terminal
|
||||
programs called :doc:`kittens <kittens_intro>`. These can be used to add features
|
||||
to kitty, for example, :doc:`editing remote files <kittens/remote_file>` or
|
||||
:doc:`inputting Unicode characters <kittens/unicode_input>`. They can also be
|
||||
used to create programs that leverage kitty's powerful features, for example,
|
||||
:doc:`viewing images <kittens/icat>` or :doc:`diffing files with image support
|
||||
<kittens/diff>`.
|
||||
kitty dispose d'un puissant framework de script. Vous pouvez créer de petits
|
||||
programmes de terminal appelés :doc:`kittens <kittens_intro>`. Ils servent à
|
||||
ajouter des fonctionnalités à kitty, par exemple :doc:`éditer des fichiers
|
||||
distants <kittens/remote_file>` ou :doc:`saisir des caractères Unicode
|
||||
<kittens/unicode_input>`. Ils peuvent aussi servir à créer des programmes
|
||||
tirant parti des puissantes fonctionnalités de kitty, par exemple
|
||||
:doc:`visualiser des images <kittens/icat>` ou :doc:`comparer des fichiers avec
|
||||
prise en charge des images <kittens/diff>`.
|
||||
|
||||
You can :doc:`create your own kittens to scratch your own itches
|
||||
Vous pouvez :doc:`créer vos propres kittens pour répondre à vos besoins
|
||||
<kittens/custom>`.
|
||||
|
||||
For a list of all the builtin kittens, run ``kitten`` in kitty, or to browse
|
||||
some of the more prominent ones, see :ref:`see here <kittens>`.
|
||||
Pour la liste de tous les kittens intégrés, lancez ``kitten`` dans kitty, ou
|
||||
pour parcourir les plus importants, voir :ref:`voir ici <kittens>`.
|
||||
|
||||
Additionally, you can use the :ref:`watchers <Watchers>` framework
|
||||
to create Python scripts that run in response to various events such as windows
|
||||
being resized, closing, having their titles changed, etc.
|
||||
De plus, vous pouvez utiliser le framework des :ref:`watchers <Watchers>` pour
|
||||
créer des scripts Python qui s'exécutent en réponse à divers événements, comme
|
||||
le redimensionnement ou la fermeture des fenêtres, la modification de leur
|
||||
titre, etc.
|
||||
|
||||
Finally, there is remote control which allows you to control kitty from
|
||||
anywhere, even across a network! See below for more about remote control.
|
||||
Enfin, il existe le contrôle à distance qui permet de piloter kitty depuis
|
||||
n'importe où, même à travers un réseau ! Voir ci-dessous pour en savoir plus
|
||||
sur le contrôle à distance.
|
||||
|
||||
.. toctree::
|
||||
:hidden:
|
||||
@@ -115,15 +129,16 @@ anywhere, even across a network! See below for more about remote control.
|
||||
kittens_intro
|
||||
|
||||
|
||||
Remote control
|
||||
------------------
|
||||
Contrôle à distance
|
||||
-------------------
|
||||
|
||||
|kitty| has a very powerful system that allows you to control it from the
|
||||
:doc:`shell prompt, even over SSH <remote-control>`. You can change colors,
|
||||
fonts, open new :term:`windows <window>`, :term:`tabs <tab>`, set their titles,
|
||||
change window layout, get text from one window and send text to another, etc.
|
||||
The possibilities are endless. See the :doc:`tutorial <remote-control>` to get
|
||||
started.
|
||||
|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
|
||||
changer les couleurs, les polices, ouvrir de nouvelles :term:`fenêtres
|
||||
<window>`, de nouveaux :term:`onglets <tab>`, définir leurs titres, changer la
|
||||
disposition des fenêtres, récupérer le texte d'une fenêtre et l'envoyer à une
|
||||
autre, etc. Les possibilités sont infinies. Voir le :doc:`tutoriel
|
||||
<remote-control>` pour démarrer.
|
||||
|
||||
.. toctree::
|
||||
:hidden:
|
||||
@@ -134,19 +149,21 @@ started.
|
||||
Sessions
|
||||
------------------
|
||||
|
||||
You can control the :term:`tabs <tab>`, :term:`kitty window <window>` layout,
|
||||
working directory, startup programs, etc. by creating a *session* file and using
|
||||
the :option:`kitty --session` command line flag or the :opt:`startup_session`
|
||||
option in :file:`kitty.conf`. You can also easily switch between sessions with
|
||||
a keypress. See :doc:`sessions` for details.
|
||||
Vous pouvez piloter les :term:`onglets <tab>`, la disposition des
|
||||
:term:`fenêtres kitty <window>`, le répertoire de travail, les programmes de
|
||||
démarrage, etc. en créant un fichier de *session* et en utilisant l'option de
|
||||
ligne de commande :option:`kitty --session` ou l'option
|
||||
:opt:`startup_session` dans :file:`kitty.conf`. Vous pouvez aussi passer
|
||||
facilement d'une session à l'autre avec une combinaison de touches. Voir
|
||||
:doc:`sessions` pour les détails.
|
||||
|
||||
|
||||
Creating tabs/windows
|
||||
-------------------------------
|
||||
Créer des onglets et des fenêtres
|
||||
---------------------------------
|
||||
|
||||
kitty can be told to run arbitrary programs in new :term:`tabs <tab>`,
|
||||
:term:`windows <window>` or :term:`overlays <overlay>` at a keypress.
|
||||
To learn how to do this, see :doc:`here <launch>`.
|
||||
kitty peut exécuter des programmes arbitraires dans de nouveaux :term:`onglets
|
||||
<tab>`, :term:`fenêtres <window>` ou :term:`surcouches <overlay>` sur une
|
||||
combinaison de touches. Pour apprendre comment faire, voir :doc:`ici <launch>`.
|
||||
|
||||
.. toctree::
|
||||
:hidden:
|
||||
@@ -154,119 +171,134 @@ To learn how to do this, see :doc:`here <launch>`.
|
||||
launch
|
||||
|
||||
|
||||
Mouse features
|
||||
-------------------
|
||||
Fonctionnalités de la souris
|
||||
----------------------------
|
||||
|
||||
* You can click on a URL to open it in a browser.
|
||||
* You can double click to select a word and then drag to select more words.
|
||||
* You can triple click to select a line and then drag to select more lines.
|
||||
* You can triple click while holding :kbd:`Ctrl+Alt` to select from clicked
|
||||
point to end of line.
|
||||
* You can right click to extend a previous selection.
|
||||
* You can hold down :kbd:`Ctrl+Alt` and drag with the mouse to select in
|
||||
columns.
|
||||
* Selecting text automatically copies it to the primary clipboard (on platforms
|
||||
with a primary clipboard).
|
||||
* You can middle click to paste from the primary clipboard (on platforms with a
|
||||
primary clipboard).
|
||||
* You can right click while holding :kbd:`Ctrl+Shift` to open the output of the
|
||||
clicked on command in a pager (requires :ref:`shell_integration`)
|
||||
* You can select text with kitty even when a terminal program has grabbed the
|
||||
mouse by holding down the :kbd:`Shift` key
|
||||
* Vous pouvez cliquer sur une URL pour l'ouvrir dans un navigateur.
|
||||
* Vous pouvez double-cliquer pour sélectionner un mot, puis glisser pour
|
||||
sélectionner d'autres mots.
|
||||
* Vous pouvez triple-cliquer pour sélectionner une ligne, puis glisser pour
|
||||
sélectionner d'autres lignes.
|
||||
* Vous pouvez triple-cliquer en maintenant :kbd:`Ctrl+Alt` pour sélectionner du
|
||||
point cliqué jusqu'à la fin de la ligne.
|
||||
* Vous pouvez faire un clic droit pour étendre une sélection précédente.
|
||||
* Vous pouvez maintenir :kbd:`Ctrl+Alt` et glisser à la souris pour
|
||||
sélectionner en colonnes.
|
||||
* Sélectionner du texte le copie automatiquement dans le presse-papiers
|
||||
primaire (sur les plateformes disposant d'un presse-papiers primaire).
|
||||
* Vous pouvez cliquer avec le bouton du milieu pour coller depuis le
|
||||
presse-papiers primaire (sur les plateformes disposant d'un presse-papiers
|
||||
primaire).
|
||||
* Vous pouvez faire un clic droit en maintenant :kbd:`Ctrl+Shift` pour ouvrir
|
||||
la sortie de la commande cliquée dans un pager (nécessite
|
||||
:ref:`shell_integration`)
|
||||
* Vous pouvez sélectionner du texte avec kitty même lorsqu'un programme du
|
||||
terminal a accaparé la souris, en maintenant la touche :kbd:`Shift`
|
||||
|
||||
All these actions can be customized in :file:`kitty.conf` as described
|
||||
:ref:`here <conf-kitty-mouse.mousemap>`.
|
||||
Toutes ces actions sont personnalisables dans :file:`kitty.conf` comme décrit
|
||||
:ref:`ici <conf-kitty-mouse.mousemap>`.
|
||||
|
||||
You can also customize what happens when clicking on :term:`hyperlinks` in
|
||||
kitty, having it open files in your editor, download remote files, open things
|
||||
in your browser, etc. For details, see :doc:`here <open_actions>`.
|
||||
Vous pouvez aussi personnaliser ce qui se passe lorsque vous cliquez sur des
|
||||
:term:`liens hypertextes <hyperlinks>` dans kitty : les ouvrir dans votre
|
||||
éditeur, télécharger des fichiers distants, les ouvrir dans votre navigateur,
|
||||
etc. Pour les détails, voir :doc:`ici <open_actions>`.
|
||||
|
||||
Additionally, various bits of the kitty UI itself work with the mouse. You can
|
||||
drag and drop tabs in the tab bar to re-order them or move them from one OS
|
||||
Window to another, or even pop them out into a new OS Window. A tab containing a
|
||||
single window can also be dropped into the content area of another tab to insert
|
||||
its window at the highlighted edge.
|
||||
De plus, divers éléments de l'interface de kitty fonctionnent à la souris. Vous
|
||||
pouvez faire glisser des onglets dans la barre d'onglets pour les réorganiser
|
||||
ou les déplacer d'une fenêtre OS à une autre, ou même les détacher dans une
|
||||
nouvelle fenêtre OS. Un onglet contenant une seule fenêtre peut aussi être
|
||||
déposé dans la zone de contenu d'un autre onglet pour y insérer sa fenêtre sur
|
||||
le bord mis en évidence.
|
||||
|
||||
Dragging a tab in the tab bar shows an insertion marker at the position it
|
||||
will be dropped at, keeping the other tabs in place during the drag. When
|
||||
dragging a tab containing a single window, hover over another tab for 0.6
|
||||
seconds to switch to it, then keep dragging into its content area to choose a
|
||||
split position for the window before releasing the mouse.
|
||||
Faire glisser un onglet dans la barre d'onglets affiche un marqueur d'insertion
|
||||
à la position où il sera déposé, en laissant les autres onglets en place
|
||||
pendant le glissement. Lorsque vous faites glisser un onglet contenant une
|
||||
seule fenêtre, survolez un autre onglet pendant 0,6 seconde pour y basculer,
|
||||
puis continuez à glisser dans sa zone de contenu pour choisir une position de
|
||||
division pour la fenêtre avant de relâcher la souris.
|
||||
|
||||
When dragging a window, hovering over the middle of a tab also switches to it,
|
||||
and dropping the window there moves it into that tab. The outer 10% at either
|
||||
end of a tab, the gaps between tabs and the ends of the tab bar show an
|
||||
insertion marker instead. Dropping a window there puts it into a new tab at
|
||||
that position.
|
||||
Lorsque vous faites glisser une fenêtre, survoler le milieu d'un onglet y
|
||||
bascule aussi, et y déposer la fenêtre l'y déplace. Les 10 % extérieurs aux
|
||||
deux extrémités d'un onglet, les espaces entre les onglets et les extrémités de
|
||||
la barre d'onglets affichent plutôt un marqueur d'insertion. Y déposer une
|
||||
fenêtre la place dans un nouvel onglet à cette position.
|
||||
|
||||
You can drag window borders to resize windows. You can double click on empty regions
|
||||
of the tab bar to create new tabs or double click on an existing tab to rename
|
||||
it.
|
||||
Vous pouvez faire glisser les bordures des fenêtres pour les redimensionner.
|
||||
Vous pouvez double-cliquer sur les zones vides de la barre d'onglets pour créer
|
||||
de nouveaux onglets, ou double-cliquer sur un onglet existant pour le renommer.
|
||||
|
||||
.. toctree::
|
||||
:hidden:
|
||||
|
||||
open_actions
|
||||
|
||||
Font control
|
||||
-----------------
|
||||
Contrôle des polices
|
||||
--------------------
|
||||
|
||||
|kitty| has extremely flexible and powerful font selection features. You can
|
||||
specify individual families for the regular, bold, italic and bold+italic fonts.
|
||||
You can even specify specific font families for specific ranges of Unicode
|
||||
characters. This allows precise control over text rendering. It can come in
|
||||
handy for applications like powerline, without the need to use patched fonts.
|
||||
See the various font related configuration directives in
|
||||
:ref:`conf-kitty-fonts`.
|
||||
|kitty| dispose de fonctionnalités de sélection de polices extrêmement
|
||||
souples et puissantes. Vous pouvez indiquer des familles individuelles pour
|
||||
les polices regular, bold, italic et bold+italic. Vous pouvez même indiquer des
|
||||
familles de polices précises pour des plages particulières de caractères
|
||||
Unicode. Cela permet un contrôle fin du rendu du texte. C'est pratique pour
|
||||
des applications comme powerline, sans avoir besoin d'utiliser des polices
|
||||
modifiées. Voir les différentes directives de configuration liées aux polices
|
||||
dans :ref:`conf-kitty-fonts`.
|
||||
|
||||
|
||||
.. _scrollback:
|
||||
|
||||
The scrollback buffer
|
||||
Le tampon d'historique
|
||||
-----------------------
|
||||
|
||||
|kitty| supports scrolling back to view history, just like most terminals. You
|
||||
can use either keyboard shortcuts or the mouse scroll wheel to do so. |kitty|
|
||||
displays an interactive :opt:`scrollbar` along the right edge
|
||||
of the window that shows your current position in the scrollback. You can click
|
||||
and drag the scrollbar to quickly navigate through the history.
|
||||
|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
|
||||
la molette de la souris. |kitty| affiche une :opt:`scrollbar`
|
||||
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
|
||||
défilement pour naviguer rapidement dans l'historique.
|
||||
|
||||
However, |kitty| has an extra, neat feature. Sometimes you need to explore the scrollback
|
||||
buffer in more detail, maybe search for some text or refer to it side-by-side
|
||||
while typing in a follow-up command. |kitty| allows you to do this by pressing
|
||||
the :sc:`show_scrollback` shortcut, which will open the scrollback buffer in
|
||||
your favorite pager program (which is :program:`less` by default). Colors and
|
||||
text formatting are preserved. You can explore the scrollback buffer comfortably
|
||||
within the pager.
|
||||
Cependant, |kitty| possède une fonctionnalité supplémentaire bien pratique.
|
||||
Parfois, vous avez besoin d'explorer le tampon d'historique plus en détail,
|
||||
peut-être pour chercher du texte ou vous y référer côte à côte pendant que vous
|
||||
tapez une commande de suivi. |kitty| vous permet de le faire en appuyant sur le
|
||||
raccourci :sc:`show_scrollback`, qui ouvre le tampon d'historique dans votre
|
||||
programme pager préféré (:program:`less` par défaut). Les couleurs et le
|
||||
formatage du texte sont préservés. Vous pouvez explorer confortablement le
|
||||
tampon d'historique dans le pager.
|
||||
|
||||
Additionally, you can pipe the contents of the scrollback buffer to an
|
||||
arbitrary, command running in a new :term:`window`, :term:`tab` or
|
||||
:term:`overlay`. For example::
|
||||
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
|
||||
:term:`onglet <tab>` ou une :term:`surcouche <overlay>`. Par exemple ::
|
||||
|
||||
map f1 launch --stdin-source=@screen_scrollback --stdin-add-formatting less +G -R
|
||||
|
||||
Would open the scrollback buffer in a new :term:`window` when you press the
|
||||
:kbd:`F1` key. See :sc:`show_scrollback <show_scrollback>` for details.
|
||||
ouvrira le tampon d'historique dans une nouvelle :term:`fenêtre <window>` lorsque
|
||||
vous
|
||||
appuyez sur la touche :kbd:`F1`. Voir :sc:`show_scrollback <show_scrollback>`
|
||||
pour les détails.
|
||||
|
||||
If you want to use it with an editor such as :program:`nvim` to get more powerful
|
||||
features, see for example, `kitty-scrollback.nvim
|
||||
<https://github.com/mikesmithgh/kitty-scrollback.nvim>`__ or `kitty-grab <https://github.com/yurikhan/kitty_grab>`__
|
||||
or see more tips for using various editor programs, in :iss:`this thread <719>`.
|
||||
Si vous voulez l'utiliser avec un éditeur comme :program:`nvim` pour obtenir
|
||||
des fonctionnalités plus puissantes, voir par exemple `kitty-scrollback.nvim
|
||||
<https://github.com/mikesmithgh/kitty-scrollback.nvim>`__ ou `kitty-grab
|
||||
<https://github.com/yurikhan/kitty_grab>`__, ou consultez d'autres astuces pour
|
||||
utiliser divers éditeurs dans :iss:`ce fil de discussion <719>`.
|
||||
|
||||
If you wish to store very large amounts of scrollback to view using the piping
|
||||
or :sc:`show_scrollback <show_scrollback>` features, you can use the
|
||||
:opt:`scrollback_pager_history_size` option.
|
||||
Si vous souhaitez conserver de très grandes quantités d'historique à consulter
|
||||
avec les fonctionnalités de redirection ou :sc:`show_scrollback
|
||||
<show_scrollback>`, vous pouvez utiliser l'option
|
||||
:opt:`scrollback_pager_history_size`.
|
||||
|
||||
|
||||
Integration with shells
|
||||
Intégration avec les shells
|
||||
---------------------------------
|
||||
|
||||
kitty has the ability to integrate closely within common shells, such as `zsh
|
||||
<https://www.zsh.org/>`__, `fish <https://fishshell.com>`__ and `bash
|
||||
<https://www.gnu.org/software/bash/>`__ to enable features such as jumping to
|
||||
previous prompts in the scrollback, viewing the output of the last command in
|
||||
:program:`less`, using the mouse to move the cursor while editing prompts, etc.
|
||||
See :doc:`shell-integration` for details.
|
||||
kitty peut s'intégrer étroitement aux shells courants, comme `zsh
|
||||
<https://www.zsh.org/>`__, `fish <https://fishshell.com>`__ et `bash
|
||||
<https://www.gnu.org/software/bash/>`__ pour activer des fonctionnalités comme
|
||||
le saut aux invites précédentes dans l'historique, la consultation de la sortie
|
||||
de la dernière commande dans :program:`less`, le déplacement du curseur à la
|
||||
souris pendant l'édition des invites, etc. Voir :doc:`shell-integration` pour
|
||||
les détails.
|
||||
|
||||
.. toctree::
|
||||
:hidden:
|
||||
@@ -275,27 +307,30 @@ See :doc:`shell-integration` for details.
|
||||
|
||||
.. _cpbuf:
|
||||
|
||||
Multiple copy/paste buffers
|
||||
-----------------------------
|
||||
Plusieurs tampons de copier/coller
|
||||
----------------------------------
|
||||
|
||||
In addition to being able to copy/paste from the system clipboard, in |kitty|
|
||||
you can also setup an arbitrary number of copy paste buffers. To do so, simply
|
||||
add something like the following to your :file:`kitty.conf`::
|
||||
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
|
||||
ce faire, ajoutez simplement quelque chose comme ce qui suit à votre
|
||||
:file:`kitty.conf` ::
|
||||
|
||||
map f1 copy_to_buffer a
|
||||
map f2 paste_from_buffer a
|
||||
|
||||
This will allow you to press :kbd:`F1` to copy the current selection to an
|
||||
internal buffer named ``a`` and :kbd:`F2` to paste from that buffer. The buffer
|
||||
names are arbitrary strings, so you can define as many such buffers as you need.
|
||||
Cela vous permettra d'appuyer sur :kbd:`F1` pour copier la sélection courante
|
||||
dans un tampon interne nommé ``a`` et sur :kbd:`F2` pour coller depuis ce
|
||||
tampon. Les noms de tampons sont des chaînes arbitraires, vous pouvez donc
|
||||
définir autant de tampons que nécessaire.
|
||||
|
||||
|
||||
Marks
|
||||
Marques
|
||||
-------------
|
||||
|
||||
kitty has the ability to mark text on the screen based on regular expressions.
|
||||
This can be useful to highlight words or phrases when browsing output from long
|
||||
running programs or similar. To learn how this feature works, see :doc:`marks`.
|
||||
kitty peut marquer du texte à l'écran à partir d'expressions régulières. C'est
|
||||
utile pour mettre en évidence des mots ou des phrases lors de la lecture de la
|
||||
sortie de programmes longs. Pour apprendre comment fonctionne cette
|
||||
fonctionnalité, voir :doc:`marks`.
|
||||
|
||||
.. toctree::
|
||||
:hidden:
|
||||
|
||||
+98
-88
@@ -1,78 +1,83 @@
|
||||
Performance
|
||||
===================
|
||||
|
||||
The main goals for |kitty| performance are user perceived latency while typing
|
||||
and "smoothness" while scrolling as well as CPU usage. |kitty| tries hard to
|
||||
find an optimum balance for these. To that end it keeps a cache of each
|
||||
rendered glyph in video RAM so that font rendering is not a bottleneck.
|
||||
Interaction with child programs takes place in a separate thread from
|
||||
rendering, to improve smoothness. Parsing of the byte stream is done using
|
||||
`vector CPU instructions
|
||||
<https://en.wikipedia.org/wiki/Single_instruction,_multiple_data>`__ for
|
||||
maximum performance. Updates to the screen typically require sending just a few
|
||||
bytes to the GPU.
|
||||
Les principaux objectifs de performance de |kitty| sont la latence perçue par
|
||||
l'utilisateur pendant la frappe, la « fluidité » pendant le défilement, ainsi
|
||||
que l'utilisation du processeur. |kitty| s'efforce de trouver un équilibre
|
||||
optimal entre ces éléments. À cette fin, il conserve un cache de chaque glyphe
|
||||
dessiné dans la mémoire vidéo, afin que le rendu des polices ne soit pas un
|
||||
goulot d'étranglement. L'interaction avec les programmes enfants se fait dans un
|
||||
thread distinct du rendu, pour améliorer la fluidité. L'analyse du flux d'octets
|
||||
est effectuée à l'aide d'`instructions vectorielles du processeur
|
||||
<https://fr.wikipedia.org/wiki/Single_instruction,_multiple_data>`__ pour des
|
||||
performances maximales. Les mises à jour de l'écran ne nécessitent
|
||||
généralement que l'envoi de quelques octets au GPU.
|
||||
|
||||
There are two config options you can tune to adjust the performance,
|
||||
:opt:`repaint_delay` and :opt:`input_delay`. These control the artificial delays
|
||||
introduced into the render loop to reduce CPU usage. See
|
||||
:ref:`conf-kitty-performance` for details. See also the :opt:`sync_to_monitor`
|
||||
option to further decrease latency at the cost of some `screen tearing
|
||||
<https://en.wikipedia.org/wiki/Screen_tearing>`__ while scrolling.
|
||||
Deux options de configuration vous permettent d'ajuster les performances :
|
||||
:opt:`repaint_delay` et :opt:`input_delay`. Elles contrôlent les délais
|
||||
artificiels introduits dans la boucle de rendu afin de réduire l'utilisation du
|
||||
processeur. Voir :ref:`conf-kitty-performance` pour les détails. Voir aussi
|
||||
l'option :opt:`sync_to_monitor` pour réduire encore la latence au prix d'un peu
|
||||
de `déchirure d'écran <https://fr.wikipedia.org/wiki/Tearing>`__ pendant le
|
||||
défilement.
|
||||
|
||||
Benchmarks
|
||||
-------------
|
||||
|
||||
Measuring terminal emulator performance is fairly subtle, there are three main
|
||||
axes on which performance is measured: Energy usage for typical tasks,
|
||||
Keyboard to screen latency, and throughput (processing large amounts of data).
|
||||
Mesurer les performances d'un émulateur de terminal est assez subtil ; il y a
|
||||
trois axes principaux sur lesquels on mesure les performances : la consommation
|
||||
d'énergie pour les tâches courantes, la latence entre le clavier et l'écran, et
|
||||
le débit (traitement de grandes quantités de données).
|
||||
|
||||
Keyboard to screen latency
|
||||
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
Latence entre le clavier et l'écran
|
||||
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
This is measured either with dedicated hardware, or software such as `Typometer
|
||||
<https://pavelfatin.com/typometer/>`__. Third party measurements comparing
|
||||
kitty with other terminal emulators on various systems show kitty has best in
|
||||
class keyboard to screen latency.
|
||||
Elle se mesure soit avec du matériel dédié, soit avec des logiciels comme
|
||||
`Typometer <https://pavelfatin.com/typometer/>`__. Les mesures de tiers
|
||||
comparant kitty à d'autres émulateurs de terminal sur divers systèmes montrent
|
||||
que kitty offre une latence clavier-écran parmi les meilleures de sa catégorie.
|
||||
|
||||
Note that to minimize latency at the expense of more energy usage, use the
|
||||
following settings in kitty.conf::
|
||||
Notez que pour minimiser la latence au prix d'une consommation d'énergie plus
|
||||
élevée, utilisez les réglages suivants dans kitty.conf ::
|
||||
|
||||
input_delay 0
|
||||
repaint_delay 2
|
||||
sync_to_monitor no
|
||||
wayland_enable_ime no
|
||||
|
||||
`Hardware based measurement on macOS
|
||||
<https://thume.ca/2020/05/20/making-a-latency-tester/>`__ show that kitty and
|
||||
Apple's Terminal.app share the crown for best latency. These
|
||||
measurements were done with :opt:`input_delay` at its default value of ``3 ms``
|
||||
which means kitty's actual numbers would be even lower.
|
||||
Les `mesures matérielles sous macOS
|
||||
<https://thume.ca/2020/05/20/making-a-latency-tester/>`__ montrent que kitty et
|
||||
Terminal.app d'Apple se partagent la couronne de la meilleure latence. Ces
|
||||
mesures ont été effectuées avec :opt:`input_delay` à sa valeur par défaut de
|
||||
``3 ms``, ce qui signifie que les chiffres réels de kitty seraient encore
|
||||
meilleurs.
|
||||
|
||||
`Typometer based measurements on Linux
|
||||
Les `mesures avec Typometer sous Linux
|
||||
<https://github.com/kovidgoyal/kitty/issues/2701#issuecomment-911089374>`__
|
||||
show that kitty has far and away the best latency of the terminals tested.
|
||||
montrent que kitty a de loin la meilleure latence des terminaux testés.
|
||||
|
||||
.. _throughput:
|
||||
|
||||
Throughput
|
||||
Débit
|
||||
^^^^^^^^^^^^^^^^
|
||||
|
||||
kitty has a builtin kitten to measure throughput, it works by dumping large
|
||||
amounts of data of different types into the tty device and measuring how fast
|
||||
the terminal parses and responds to it. The measurements below were taken with
|
||||
the same font, font size and window size for all terminals, and default
|
||||
settings, on the same computer. They clearly show kitty has the fastest
|
||||
throughput. To run the tests yourself, run ``kitten __benchmark__`` in the
|
||||
terminal emulator you want to test, where the kitten binary is part of the
|
||||
kitty install.
|
||||
kitty intègre un kitten permettant de mesurer le débit : il envoie de grandes
|
||||
quantités de données de différents types au périphérique tty et mesure la
|
||||
vitesse avec laquelle le terminal les analyse et y répond. Les mesures
|
||||
ci-dessous ont été prises avec la même police, la même taille de police et la
|
||||
même taille de fenêtre pour tous les terminaux, avec les réglages par défaut,
|
||||
sur le même ordinateur. Elles montrent clairement que kitty a le débit le plus
|
||||
élevé. Pour lancer les tests vous-même, exécutez ``kitten __benchmark__`` dans
|
||||
l'émulateur de terminal que vous voulez tester, le binaire kitten faisant
|
||||
partie de l'installation de kitty.
|
||||
|
||||
The numbers are megabytes per second of data that the terminal
|
||||
processes. Measurements were taken under Linux/X11 with an ``AMD Ryzen 7 PRO
|
||||
5850U``. Entries are in order of decreasing performance. kitty is twice
|
||||
as fast as the next best.
|
||||
Les chiffres sont des mégaoctets par seconde de données traitées par le
|
||||
terminal. Les mesures ont été prises sous Linux/X11 avec un ``AMD Ryzen 7 PRO
|
||||
5850U``. Les entrées sont classées par performances décroissantes. kitty est
|
||||
deux fois plus rapide que le deuxième meilleur.
|
||||
|
||||
================ ====== ======= ===== ====== =======
|
||||
Terminal ASCII Unicode CSI Images Average
|
||||
Terminal ASCII Unicode CSI Images Moyenne
|
||||
================ ====== ======= ===== ====== =======
|
||||
kitty 0.33 121.8 105.0 59.8 251.6 134.55
|
||||
gnometerm 3.50.1 33.4 55.0 16.1 142.8 61.83
|
||||
@@ -83,74 +88,79 @@ konsole 23.08.04 25.2 37.7 23.6 23.4 27.48
|
||||
alacritty+tmux 30.3 7.8 14.7 46.1 24.73
|
||||
================ ====== ======= ===== ====== =======
|
||||
|
||||
In this table, each column represents different types of data. The CSI column
|
||||
is for data consisting of a mix of typical formatting escape codes and some
|
||||
ASCII only text.
|
||||
Dans ce tableau, chaque colonne représente différents types de données. La
|
||||
colonne CSI concerne des données constituées d'un mélange de codes
|
||||
d'échappement de formatage typiques et de texte uniquement ASCII.
|
||||
|
||||
.. note::
|
||||
|
||||
By default, the benchmark kitten suppresses actual rendering, to better
|
||||
focus on parser speed, you can pass it the ``--render`` flag to not suppress
|
||||
rendering. However, modern terminals typically render asynchronously,
|
||||
therefore the numbers are not really useful for comparison, as it is just a
|
||||
game about how much input to *batch* before rendering the next frame.
|
||||
However, even with rendering enabled kitty is still faster than all the
|
||||
rest. For brevity those numbers are not included.
|
||||
Par défaut, le kitten de benchmark supprime le rendu réel afin de se
|
||||
concentrer sur la vitesse de l'analyseur ; vous pouvez lui passer l'option
|
||||
``--render`` pour ne pas supprimer le rendu. Cependant, les terminaux
|
||||
modernes dessinent généralement de façon asynchrone, donc les chiffres ne
|
||||
sont pas vraiment utiles pour la comparaison, car il s'agit juste de savoir
|
||||
combien d'entrées *regrouper* avant de dessiner l'image suivante. Toutefois,
|
||||
même avec le rendu activé, kitty reste plus rapide que tous les autres. Par
|
||||
souci de concision, ces chiffres ne sont pas inclus.
|
||||
|
||||
.. note::
|
||||
|
||||
foot, iterm2 and Terminal.app are left out as they do not run under X11.
|
||||
Alacritty+tmux is included just to show the effect of putting a terminal
|
||||
multiplexer into the mix (halving throughput) and because alacritty isn't
|
||||
remotely comparable to any of the other terminals feature wise without tmux.
|
||||
foot, iterm2 et Terminal.app sont omis car ils ne fonctionnent pas sous X11.
|
||||
Alacritty+tmux est inclus uniquement pour montrer l'effet de l'ajout d'un
|
||||
multiplexeur de terminal dans l'équation (débit divisé par deux) et parce
|
||||
qu'alacritty n'est pas du tout comparable aux autres terminaux en termes de
|
||||
fonctionnalités sans tmux.
|
||||
|
||||
.. note::
|
||||
|
||||
konsole, gnome-terminal and xterm do not support the `Synchronized update
|
||||
konsole, gnome-terminal et xterm ne prennent pas en charge le code
|
||||
d'échappement de `mise à jour synchronisée
|
||||
<https://gitlab.com/gnachman/iterm2/-/wikis/synchronized-updates-spec>`__
|
||||
escape code used to suppress rendering, if and when they gain support for it
|
||||
their numbers are likely to improve by ``20 - 50%``, depending on how well they
|
||||
implement it.
|
||||
utilisé pour supprimer le rendu ; s'ils venaient à le prendre en charge,
|
||||
leurs chiffres s'amélioreraient probablement de ``20 - 50%``, selon la
|
||||
qualité de leur implémentation.
|
||||
|
||||
|
||||
Energy usage
|
||||
^^^^^^^^^^^^^^^^^
|
||||
Consommation d'énergie
|
||||
^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
Sadly, I do not have the infrastructure to measure actual energy usage so CPU
|
||||
usage will have to stand in for it. Here are some CPU usage numbers for the
|
||||
task of scrolling a file continuously in :program:`less`. The CPU usage is for
|
||||
the terminal process and X together and is measured using :program:`htop`. The
|
||||
measurements are taken at the same font and window size for all terminals on a
|
||||
``Intel(R) Core(TM) i7-4820K CPU @ 3.70GHz`` CPU with a ``Advanced Micro
|
||||
Devices, Inc. [AMD/ATI] Cape Verde XT [Radeon HD 7770/8760 / R7 250X]`` GPU.
|
||||
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
|
||||
quelques chiffres d'utilisation du processeur pour la tâche consistant à faire
|
||||
défiler un fichier en continu dans :program:`less`. L'utilisation du processeur
|
||||
concerne le processus du terminal et X ensemble et est mesurée avec
|
||||
:program:`htop`. Les mesures ont été prises avec la même police et la même
|
||||
taille de fenêtre pour tous les terminaux sur un processeur ``Intel(R) Core(TM)
|
||||
i7-4820K CPU @ 3.70GHz`` avec un GPU ``Advanced Micro Devices, Inc.
|
||||
[AMD/ATI] Cape Verde XT [Radeon HD 7770/8760 / R7 250X]``.
|
||||
|
||||
============== =========================
|
||||
Terminal CPU usage (X + terminal)
|
||||
============== =========================
|
||||
============== ============================
|
||||
Terminal Utilisation CPU (X + terminal)
|
||||
============== ============================
|
||||
|kitty| 6 - 8%
|
||||
xterm 5 - 7% (but scrolling was extremely janky)
|
||||
xterm 5 - 7% (mais le défilement était extrêmement saccadé)
|
||||
termite 10 - 13%
|
||||
urxvt 12 - 14%
|
||||
gnome-terminal 15 - 17%
|
||||
konsole 29 - 31%
|
||||
============== =========================
|
||||
============== ============================
|
||||
|
||||
As you can see, |kitty| uses much less CPU than all terminals, except xterm, but
|
||||
its scrolling "smoothness" is much better than that of xterm (at least to my,
|
||||
admittedly biased, eyes).
|
||||
Comme vous pouvez le voir, |kitty| utilise bien moins de processeur que tous
|
||||
les terminaux, sauf xterm, mais sa « fluidité » de défilement est bien
|
||||
meilleure que celle d'xterm (du moins à mes yeux, il est vrai, subjectifs).
|
||||
|
||||
Instrumenting kitty
|
||||
Instrumenter kitty
|
||||
-----------------------
|
||||
|
||||
To profile kitty performance on Linux, first install ``perf`` and run::
|
||||
Pour profiler les performances de kitty sous Linux, installez d'abord ``perf``
|
||||
et lancez ::
|
||||
|
||||
sudo setcap cap_sys_admin,cap_sys_ptrace,cap_syslog=ep /usr/bin/perf
|
||||
|
||||
Then build kitty with::
|
||||
Compilez ensuite kitty avec ::
|
||||
|
||||
make profile
|
||||
|
||||
Finally get benchmark and profiling results using::
|
||||
Enfin, obtenez les résultats de benchmark et de profilage avec ::
|
||||
|
||||
./benchmark.py --perf
|
||||
|
||||
@@ -34,6 +34,30 @@ you want to work on the project, simply run:
|
||||
|
||||
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
|
||||
create more complex sessions, see :ref:`complex_sessions`.
|
||||
|
||||
|
||||
+16
-15
@@ -1,21 +1,22 @@
|
||||
Support kitty development ❤️
|
||||
==============================
|
||||
Soutenez le développement de kitty ❤️
|
||||
=====================================
|
||||
|
||||
My goal with |kitty| is to move the stagnant terminal ecosystem forward. To that
|
||||
end kitty has many foundational features, such as: :doc:`image support
|
||||
<graphics-protocol>`, :doc:`superlative performance <performance>`,
|
||||
:doc:`various enhancements to the terminal protocol <protocol-extensions>`,
|
||||
etc. These features allow the development of rich terminal applications, such
|
||||
as :doc:`Side-by-side diff <kittens/diff>` and :doc:`Unicode input
|
||||
<kittens/unicode_input>`.
|
||||
Mon objectif avec |kitty| est de faire avancer l'écosystème stagnant des
|
||||
terminaux. Dans cette optique, kitty possède de nombreuses fonctionnalités
|
||||
fondamentales, telles que : :doc:`la prise en charge des images
|
||||
<graphics-protocol>`, :doc:`des performances inégalées <performance>`,
|
||||
:doc:`diverses améliorations du protocole des terminaux <protocol-extensions>`,
|
||||
etc. Ces fonctionnalités permettent le développement d'applications de terminal
|
||||
riches, comme :doc:`le diff côte à côte <kittens/diff>` et :doc:`la saisie
|
||||
Unicode <kittens/unicode_input>`.
|
||||
|
||||
If you wish to support this mission and see the terminal ecosystem evolve,
|
||||
consider donating so that I can devote more time to |kitty| development.
|
||||
I have personally written `almost all kitty code
|
||||
<https://github.com/kovidgoyal/kitty/graphs/contributors>`_.
|
||||
Si vous souhaitez soutenir cette mission et voir évoluer l'écosystème des
|
||||
terminaux, envisagez un don afin que je puisse consacrer plus de temps au
|
||||
développement de |kitty|. J'ai personnellement écrit `presque tout le code de
|
||||
kitty <https://github.com/kovidgoyal/kitty/graphs/contributors>`_.
|
||||
|
||||
You can choose to make either a one-time payment via PayPal or become a
|
||||
*patron* of kitty development via one of the services below:
|
||||
Vous pouvez choisir d'effectuer un paiement unique via PayPal ou de devenir
|
||||
*patron* du développement de kitty via l'un des services ci-dessous :
|
||||
|
||||
|
||||
.. raw:: html
|
||||
|
||||
+285
-37
@@ -38,6 +38,15 @@ type InputData struct {
|
||||
Mouse []Binding `json:"mouse"`
|
||||
ModeOrder []string `json:"mode_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
|
||||
@@ -211,28 +220,57 @@ type displayLine struct {
|
||||
|
||||
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.
|
||||
const unmappedLabel = "(unmapped)"
|
||||
|
||||
// truncateToWidth truncates s to fit within maxWidth cells, appending "..." if
|
||||
// truncated and maxWidth > 3. When maxWidth <= 3, the string is simply trimmed
|
||||
// to fit without appending ellipsis (no room for it).
|
||||
// ellipsis marks a truncated string. It is a single cell, so that as much of the
|
||||
// original text as possible is kept inside the panel.
|
||||
const ellipsis = "…"
|
||||
|
||||
// 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 {
|
||||
if wcswidth.Stringwidth(s) <= maxWidth {
|
||||
return s
|
||||
}
|
||||
ellipsisWidth := wcswidth.Stringwidth(ellipsis)
|
||||
runes := []rune(s)
|
||||
if maxWidth <= 3 {
|
||||
// Not enough room for ellipsis; just trim to fit
|
||||
if maxWidth <= ellipsisWidth {
|
||||
// Not enough room for the ellipsis; just trim to fit
|
||||
for len(runes) > 0 && wcswidth.Stringwidth(string(runes)) > maxWidth {
|
||||
runes = runes[:len(runes)-1]
|
||||
}
|
||||
return string(runes)
|
||||
}
|
||||
for len(runes) > 0 && wcswidth.Stringwidth(string(runes))+3 > maxWidth {
|
||||
for len(runes) > 0 && wcswidth.Stringwidth(string(runes))+ellipsisWidth > maxWidth {
|
||||
runes = runes[:len(runes)-1]
|
||||
}
|
||||
return string(runes) + "..."
|
||||
return string(runes) + ellipsis
|
||||
}
|
||||
|
||||
// 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 ─────────".
|
||||
@@ -275,6 +313,13 @@ type Handler struct {
|
||||
cv *utils.CachedValues[*CachedSettings]
|
||||
shortcut_tracker config.ShortcutTracker
|
||||
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.
|
||||
@@ -287,17 +332,39 @@ func (h *Handler) initialize() (string, error) {
|
||||
h.lp.SetCursorVisible(true)
|
||||
h.lp.SetCursorShape(loop.BAR_CURSOR, true)
|
||||
h.lp.AllowLineWrapping(false)
|
||||
h.lp.SetWindowTitle("Command Palette")
|
||||
title := "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)
|
||||
|
||||
// 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
|
||||
if h.read_only {
|
||||
// A reference panel is about bindings, not about actions without one.
|
||||
h.show_unmapped = false
|
||||
} else if h.input_data.Leader != nil {
|
||||
// The leader panel lists exactly the keys that are available.
|
||||
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)
|
||||
|
||||
if err := h.loadData(); err != nil {
|
||||
if h.data_file != "" {
|
||||
if err := h.loadDataFile(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
} else if err := h.loadData(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
@@ -313,17 +380,48 @@ func (h *Handler) loadData() error {
|
||||
if err != nil {
|
||||
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 {
|
||||
return fmt.Errorf("no input data received on stdin; this kitten must be launched from kitty")
|
||||
return fmt.Errorf("no keybinding data received")
|
||||
}
|
||||
if err := json.Unmarshal(data, &h.input_data); err != nil {
|
||||
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()
|
||||
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
|
||||
// words for word-level matching.
|
||||
func bindingToDisplayItem(b Binding) DisplayItem {
|
||||
@@ -565,17 +663,30 @@ func (h *Handler) draw_screen() {
|
||||
h.lp.QueueWriteString(h.query)
|
||||
|
||||
// Draw results
|
||||
if h.query == "" {
|
||||
if h.leader != nil {
|
||||
h.drawFlatResults(resultsStartY, resultsHeight, width)
|
||||
} else if h.query == "" {
|
||||
h.drawGroupedResults(resultsStartY, resultsHeight, width)
|
||||
} else {
|
||||
h.drawFlatResults(resultsStartY, resultsHeight, width)
|
||||
}
|
||||
|
||||
// Draw help text for selected binding
|
||||
// Draw help text for selected binding, falling back to the full action name
|
||||
// when the action column had to ellipsize it
|
||||
h.lp.MoveCursorTo(1, helpY)
|
||||
if b := h.selectedBinding(); b != nil && b.Help != "" {
|
||||
helpStr := truncateToWidth(b.Help, max(width-2, 3))
|
||||
h.lp.QueueWriteString(h.lp.SprintStyled("dim italic", " "+helpStr))
|
||||
if b := h.selectedBinding(); b != nil {
|
||||
detail := b.Help
|
||||
if full := h.selectedActionText(); wcswidth.Stringwidth(full) > h.actionColumnWidth(width, b) {
|
||||
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
|
||||
@@ -584,10 +695,25 @@ func (h *Handler) draw_screen() {
|
||||
if h.show_unmapped {
|
||||
unmappedToggleLabel = "Hide"
|
||||
}
|
||||
footer := h.lp.SprintStyled("fg=bright-yellow", "[Enter]") + " Run " +
|
||||
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"
|
||||
footer := ""
|
||||
if h.leader != nil {
|
||||
footer = h.lp.SprintStyled("fg=bright-yellow", "[Esc]") + " Close " +
|
||||
h.lp.SprintStyled("fg=bright-yellow", "\u2191\u2193") + " Navigate " +
|
||||
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 := ""
|
||||
if h.query != "" {
|
||||
matchCount = fmt.Sprintf(" %d/%d", len(h.filtered_idx), len(h.all_items))
|
||||
@@ -662,7 +788,9 @@ func (h *Handler) drawFlatResults(startY, maxRows, width int) {
|
||||
b := &item.binding
|
||||
keyDisplay := keyDisplayText(b)
|
||||
catSuffix := ""
|
||||
if b.Mode != "" {
|
||||
if h.leader != nil {
|
||||
// Leader rows have no category to disambiguate.
|
||||
} else if b.Mode != "" {
|
||||
catSuffix = fmt.Sprintf(" [%s/%s]", b.Mode, b.Category)
|
||||
} else {
|
||||
catSuffix = fmt.Sprintf(" [%s]", b.Category)
|
||||
@@ -775,8 +903,9 @@ func (h *Handler) drawBindingLine(filteredIdx, width int, isSelected bool) {
|
||||
b := &h.all_items[idx].binding
|
||||
actionDisplay := h.all_items[idx].actionText
|
||||
|
||||
// Build the key display
|
||||
keyDisplay := keyDisplayText(b)
|
||||
// Build the key display, bounded by the room the panel leaves as well
|
||||
keyWidth := keyWidthFor(width)
|
||||
keyDisplay := truncateToWidth(keyDisplayText(b), keyWidth)
|
||||
|
||||
// Determine match info for highlighting (only set when a query is active)
|
||||
var mi *matchInfo
|
||||
@@ -805,8 +934,8 @@ func (h *Handler) drawBindingLine(filteredIdx, width int, isSelected bool) {
|
||||
return s
|
||||
}
|
||||
|
||||
// Render key column (4-space indent + key padded to maxKeyDisplayWidth + space)
|
||||
paddingLen := max(0, maxKeyDisplayWidth-wcswidth.Stringwidth(keyDisplay))
|
||||
// Render key column (4-space indent + key padded to the key column width)
|
||||
paddingLen := max(0, keyWidth-wcswidth.Stringwidth(keyDisplay))
|
||||
pad := strings.Repeat(" ", paddingLen) + " "
|
||||
ks := keyStyle
|
||||
if b.Key == "" {
|
||||
@@ -820,7 +949,8 @@ func (h *Handler) drawBindingLine(filteredIdx, width int, isSelected bool) {
|
||||
h.lp.QueueWriteString(h.lp.SprintStyled(ks, " "+keyDisplay+pad))
|
||||
}
|
||||
|
||||
// Render action display column
|
||||
// Render action display column, bounded by the room the panel leaves
|
||||
actionDisplay = truncateToWidth(actionDisplay, h.actionColumnWidth(width, b))
|
||||
if mi != nil && len(mi.actionPositions) > 0 {
|
||||
h.lp.QueueWriteString(h.highlightMatchedChars(actionDisplay, mi.actionPositions, baseStyle, matchStyle))
|
||||
} else {
|
||||
@@ -828,14 +958,14 @@ func (h *Handler) drawBindingLine(filteredIdx, width int, isSelected bool) {
|
||||
}
|
||||
|
||||
// Render category suffix (only present in flat / search-results mode)
|
||||
if h.query != "" {
|
||||
if h.query != "" && h.leader == nil {
|
||||
h.drawCategorySuffix(b, mi, baseStyle, matchStyle)
|
||||
}
|
||||
|
||||
// For selected rows, pad the rest of the line with reverse video
|
||||
if isSelected {
|
||||
rendered := 4 + wcswidth.Stringwidth(keyDisplay) + paddingLen + 1 + wcswidth.Stringwidth(actionDisplay)
|
||||
if h.query != "" {
|
||||
if h.query != "" && h.leader == nil {
|
||||
rendered += categorySuffixWidth(b)
|
||||
}
|
||||
if pad := width - rendered; pad > 0 {
|
||||
@@ -844,6 +974,19 @@ 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
|
||||
// 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
|
||||
@@ -883,6 +1026,25 @@ func (h *Handler) onMouseEvent(ev *loop.MouseEvent) error {
|
||||
|
||||
// onKeyEvent handles keyboard input for navigation, selection, and query editing.
|
||||
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") {
|
||||
ev.Handled = true
|
||||
if h.query != "" {
|
||||
@@ -904,11 +1066,16 @@ func (h *Handler) onKeyEvent(ev *loop.KeyEvent) error {
|
||||
h.moveSelection(-1)
|
||||
return nil
|
||||
}
|
||||
if ev.MatchesPressOrRepeat("down") {
|
||||
if ev.MatchesPressOrRepeat("down") || ev.MatchesPressOrRepeat("tab") {
|
||||
ev.Handled = true
|
||||
h.moveSelection(1)
|
||||
return nil
|
||||
}
|
||||
if ev.MatchesPressOrRepeat("shift+tab") {
|
||||
ev.Handled = true
|
||||
h.moveSelection(-1)
|
||||
return nil
|
||||
}
|
||||
if ac := h.shortcut_tracker.Match(ev, h.keyboard_shortcuts); ac != nil {
|
||||
ev.Handled = true
|
||||
switch ac.Name {
|
||||
@@ -958,6 +1125,24 @@ func (h *Handler) onKeyEvent(ev *loop.KeyEvent) error {
|
||||
}
|
||||
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") {
|
||||
ev.Handled = true
|
||||
h.show_unmapped = !h.show_unmapped
|
||||
@@ -972,8 +1157,19 @@ func (h *Handler) onKeyEvent(ev *loop.KeyEvent) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// onText handles typed characters, appending them to the search query.
|
||||
// onText handles typed characters, appending them to the search query, or
|
||||
// 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 {
|
||||
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.updateFilter()
|
||||
h.draw_screen()
|
||||
@@ -998,8 +1194,55 @@ func (h *Handler) moveSelection(delta int) {
|
||||
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.
|
||||
func (h *Handler) triggerSelected() {
|
||||
if h.read_only {
|
||||
h.lp.Beep()
|
||||
return
|
||||
}
|
||||
b := h.selectedBinding()
|
||||
if b == nil || b.IsMouse {
|
||||
h.lp.Beep()
|
||||
@@ -1011,7 +1254,7 @@ func (h *Handler) triggerSelected() {
|
||||
|
||||
// main runs the command palette TUI as a kitty overlay.
|
||||
func main(cmd *cli.Command, opts *Options, args []string) (rc int, err error) {
|
||||
if tty.IsTerminal(os.Stdin.Fd()) {
|
||||
if opts.DataFile == "" && 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")
|
||||
}
|
||||
output := tui.KittenOutputSerializer()
|
||||
@@ -1020,7 +1263,7 @@ func main(cmd *cli.Command, opts *Options, args []string) (rc int, err error) {
|
||||
return 1, err
|
||||
}
|
||||
|
||||
handler := &Handler{lp: lp}
|
||||
handler := &Handler{lp: lp, read_only: opts.ReadOnly, data_file: opts.DataFile}
|
||||
lp.MouseTrackingMode(loop.FULL_MOUSE_TRACKING)
|
||||
|
||||
lp.OnInitialize = func() (string, error) {
|
||||
@@ -1043,7 +1286,12 @@ func main(cmd *cli.Command, opts *Options, args []string) (rc int, err error) {
|
||||
return
|
||||
}
|
||||
rc = lp.ExitCode()
|
||||
if handler.result != "" {
|
||||
if handler.remap_key != "" {
|
||||
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})
|
||||
if serr == nil {
|
||||
fmt.Println(s)
|
||||
|
||||
@@ -318,6 +318,52 @@ 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:
|
||||
raise SystemExit('This kitten must be used only from a kitty.conf mapping')
|
||||
|
||||
@@ -330,7 +376,21 @@ def callback(target_window_id: int, action: str, timer_id: int | None) -> None:
|
||||
|
||||
@result_handler(has_ready_notification=True)
|
||||
def handle_result(args: list[str], data: dict[str, Any], target_window_id: int, boss: BossType) -> None:
|
||||
if data and (action := data.get('action')):
|
||||
if not data:
|
||||
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
|
||||
add_timer(partial(callback, target_window_id, action), 0, False)
|
||||
|
||||
@@ -338,6 +398,15 @@ def handle_result(args: list[str], data: dict[str, Any], target_window_id: int,
|
||||
help_text = 'Browse and trigger keyboard shortcuts and actions'
|
||||
usage = ''
|
||||
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
|
||||
|
||||
|
||||
|
||||
@@ -5,6 +5,9 @@ import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/tui/loop"
|
||||
"github.com/kovidgoyal/kitty/tools/wcswidth"
|
||||
)
|
||||
|
||||
// testBinding creates a Binding where Action, ActionDisplay, and Definition all
|
||||
@@ -74,6 +77,26 @@ func (b *testHandlerBuilder) build() *Handler {
|
||||
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 {
|
||||
return newBuilder().
|
||||
addBinding("", "Copy/paste", testBinding("ctrl+shift+c", "copy_to_clipboard", "Copy the selected text from the active window to the clipboard")).
|
||||
@@ -100,6 +123,48 @@ func newTestHandler() *Handler {
|
||||
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) {
|
||||
h := newTestHandler()
|
||||
// 5 default mode + 2 mw mode + 2 mouse = 9
|
||||
@@ -371,13 +436,13 @@ func TestTruncateToWidth(t *testing.T) {
|
||||
t.Fatalf("Expected %q unchanged at exact width, got %q", "hello", got)
|
||||
}
|
||||
|
||||
// Over width: truncated with ellipsis
|
||||
// Over width: truncated with a single cell ellipsis
|
||||
got = truncateToWidth("hello world", 8)
|
||||
if !strings.HasSuffix(got, "...") {
|
||||
t.Fatalf("Expected truncated string to end with '...', got %q", got)
|
||||
if !strings.HasSuffix(got, ellipsis) {
|
||||
t.Fatalf("Expected truncated string to end with %q, got %q", ellipsis, got)
|
||||
}
|
||||
if len([]rune(got)) > 8 {
|
||||
t.Fatalf("Expected truncated string to be at most 8 runes, got %d in %q", len([]rune(got)), got)
|
||||
if wcswidth.Stringwidth(got) > 8 {
|
||||
t.Fatalf("Expected truncated string to be at most 8 cells, got %d in %q", wcswidth.Stringwidth(got), got)
|
||||
}
|
||||
|
||||
// Long key like a mouse binding should be truncated
|
||||
@@ -386,8 +451,69 @@ func TestTruncateToWidth(t *testing.T) {
|
||||
if len([]rune(got)) > maxKeyDisplayWidth {
|
||||
t.Fatalf("Key should be truncated to maxKeyDisplayWidth, got len=%d: %q", len([]rune(got)), got)
|
||||
}
|
||||
if !strings.HasSuffix(got, "...") {
|
||||
t.Fatalf("Truncated key should end with '...', got %q", got)
|
||||
if !strings.HasSuffix(got, ellipsis) {
|
||||
t.Fatalf("Truncated key should end with %q, got %q", ellipsis, 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))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Whitespace-only changes.
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,269 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPL v3 Copyright: 2026, FWS
|
||||
|
||||
import shlex
|
||||
import sys
|
||||
from functools import partial
|
||||
from typing import Any
|
||||
|
||||
from kitty.conf.types import Definition
|
||||
from kitty.constants import appname
|
||||
from kitty.simple_cli_definitions import CONFIG_HELP, CompletionSpec
|
||||
from kitty.typing_compat import BossType
|
||||
|
||||
from ..tui.handler import result_handler
|
||||
|
||||
definition = Definition(
|
||||
'!kittens.file_manager',
|
||||
)
|
||||
|
||||
agr = definition.add_group
|
||||
egr = definition.end_group
|
||||
opt = definition.add_option
|
||||
map = definition.add_map
|
||||
|
||||
agr('appearance', 'Appearance')
|
||||
|
||||
opt(
|
||||
'show_hidden',
|
||||
'no',
|
||||
option_type='to_bool',
|
||||
long_text="""
|
||||
Show entries whose name starts with a full stop when the panel opens. The setting
|
||||
can be toggled at runtime with the :ref:`toggle_hidden <file-manager-shortcuts>`
|
||||
shortcut.
|
||||
""",
|
||||
)
|
||||
|
||||
opt(
|
||||
'sort_by',
|
||||
'name',
|
||||
long_text="""
|
||||
How to order entries. :code:`name` lists directories first, then files, both
|
||||
sorted by name ignoring case. :code:`mtime` lists directories first, then files
|
||||
sorted by last modification time, most recent first. :code:`size` lists
|
||||
directories first, then files sorted by size, largest first.
|
||||
""",
|
||||
)
|
||||
|
||||
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')
|
||||
|
||||
opt(
|
||||
'editor',
|
||||
'',
|
||||
long_text="""
|
||||
Deprecated and ignored. Files are opened through kitty's edit protocol, so the
|
||||
editor is the :opt:`editor` option of :file:`kitty.conf`, with :envvar:`VISUAL`
|
||||
then :envvar:`EDITOR` used when it is :code:`.` (the default). The option is
|
||||
still accepted so that existing configuration files keep loading.
|
||||
""",
|
||||
)
|
||||
|
||||
opt(
|
||||
'open_with_sudo',
|
||||
'no',
|
||||
option_type='to_bool',
|
||||
long_text="""
|
||||
Deprecated and ignored. kitty's edit protocol sends the file back when the
|
||||
editor exits and therefore needs a file the user can write to. Open privileged
|
||||
files with :code:`sudo -e` from the shell instead.
|
||||
""",
|
||||
)
|
||||
|
||||
egr()
|
||||
|
||||
agr('shortcuts', 'Keyboard shortcuts')
|
||||
|
||||
map('Quit without changing directory', 'quit q quit')
|
||||
map('Quit without changing directory', 'quit esc quit')
|
||||
map('Move selection up', 'move_up up move_up')
|
||||
map('Move selection up', 'move_up --allow-fallback=shifted,ascii k move_up')
|
||||
map('Move selection down', 'move_down down move_down')
|
||||
map('Move selection down', 'move_down --allow-fallback=shifted,ascii j move_down')
|
||||
map('Move selection up', 'move_up shift+tab move_up')
|
||||
map('Move selection down', 'move_down tab move_down')
|
||||
map('Move selection up by a page', 'page_up page_up page_up')
|
||||
map('Move selection up by a page', 'page_up --allow-fallback=shifted,ascii ctrl+b page_up')
|
||||
map('Move selection down by a page', 'page_down page_down page_down')
|
||||
map('Move selection down by a page', 'page_down --allow-fallback=shifted,ascii ctrl+f page_down')
|
||||
map('Select first entry', 'home home home')
|
||||
map('Select first entry', 'home --allow-fallback=shifted,ascii g home')
|
||||
map('Select last entry', 'end end end')
|
||||
map('Select last entry', 'end shift+g end')
|
||||
map(
|
||||
'Open the selection',
|
||||
'activate enter activate',
|
||||
long_text="""
|
||||
When the selection is a directory it is opened in the panel, exactly like the
|
||||
:ref:`enter_dir <file-manager-shortcuts>` shortcut. When it is a file, the panel
|
||||
opens it in kitty's editor (:opt:`editor`, :envvar:`VISUAL` or
|
||||
:envvar:`EDITOR`) in a new tab, and is drawn again with the same selection once
|
||||
the editor exits. The new tab is what gives the file a whole window even when
|
||||
the panel runs in a dock.
|
||||
""",
|
||||
)
|
||||
map(
|
||||
'Browse into the selected directory',
|
||||
'enter_dir right enter_dir',
|
||||
long_text="""
|
||||
Move the panel into the selected directory without changing the shell's working
|
||||
directory. Use the :ref:`cd_here <file-manager-shortcuts>` shortcut to also
|
||||
change the shell's directory.
|
||||
""",
|
||||
)
|
||||
map('Browse into the selected directory', 'enter_dir --allow-fallback=shifted,ascii l enter_dir')
|
||||
map('Browse into the parent directory', 'parent_dir left parent_dir')
|
||||
map('Browse into the parent directory', 'parent_dir backspace parent_dir')
|
||||
map('Browse into the parent directory', 'parent_dir --allow-fallback=shifted,ascii h parent_dir')
|
||||
map(
|
||||
'Change shell directory to the directory being browsed',
|
||||
'cd_here ctrl+enter cd_here',
|
||||
long_text="""
|
||||
Changes the shell's working directory to the directory currently shown in the
|
||||
panel, regardless of the selection.
|
||||
""",
|
||||
)
|
||||
map('Change shell directory to the directory being browsed', 'cd_here --allow-fallback=shifted,ascii c cd_here')
|
||||
map('Toggle display of hidden entries', 'toggle_hidden --allow-fallback=shifted,ascii . toggle_hidden')
|
||||
map('Create a new file', 'create_file --allow-fallback=shifted,ascii n create_file')
|
||||
map('Create a new directory', 'create_dir shift+n create_dir')
|
||||
map('Create a new directory', 'create_dir --allow-fallback=shifted,ascii a create_dir')
|
||||
map('Rename the selected entry', 'rename --allow-fallback=shifted,ascii r rename')
|
||||
map(
|
||||
'Delete the selected entry',
|
||||
'delete --allow-fallback=shifted,ascii d delete',
|
||||
long_text="""
|
||||
Deletes a file, a symbolic link or an empty directory after asking for
|
||||
confirmation. Directories are never deleted recursively.
|
||||
""",
|
||||
)
|
||||
map('Copy the path of the selection to the clipboard', 'copy_path --allow-fallback=shifted,ascii y copy_path')
|
||||
map('Reload the current directory', 'refresh --allow-fallback=shifted,ascii ctrl+r refresh')
|
||||
map(
|
||||
'Filter the listing with a fuzzy query',
|
||||
'search --allow-fallback=shifted,ascii / search',
|
||||
long_text="""
|
||||
Filters the listing as text is typed, using the same fuzzy matcher as the
|
||||
command palette. :kbd:`Entrée` opens the selection, :kbd:`Échap` clears the
|
||||
query and restores the full listing.
|
||||
""",
|
||||
)
|
||||
map(
|
||||
'List and run the actions of the panel',
|
||||
'palette --allow-fallback=shifted,ascii : palette',
|
||||
long_text="""
|
||||
Lists every action of the panel with its description, filtered by a fuzzy query,
|
||||
and runs the selected one with :kbd:`Entrée`. The same actions can be bound to
|
||||
dedicated shortcuts in :file:`file-manager.conf`.
|
||||
""",
|
||||
)
|
||||
map('Open the selected file in a new tab', 'open_tab --allow-fallback=shifted,ascii o open_tab')
|
||||
map('Open the selected file in a new OS window', 'open_window --allow-fallback=shifted,ascii t open_window')
|
||||
|
||||
egr()
|
||||
|
||||
OPTIONS = partial(
|
||||
"""\
|
||||
--start-dir
|
||||
Directory to start browsing in. Defaults to the current working directory.
|
||||
|
||||
|
||||
--show-hidden
|
||||
type=bool-set
|
||||
Show hidden files when the panel opens.
|
||||
|
||||
|
||||
--open-here
|
||||
type=bool-set
|
||||
Deprecated and ignored. Files are always opened in a new tab, so this flag is
|
||||
only accepted so that existing mappings keep working.
|
||||
|
||||
|
||||
--config -c
|
||||
type=list
|
||||
completion=type:file ext:conf group:"Config files" kwds:none,NONE
|
||||
{config_help}
|
||||
|
||||
|
||||
--override -o
|
||||
type=list
|
||||
Override individual configuration options, can be specified multiple times.
|
||||
Syntax: :italic:`name=value`. For example: :italic:`-o show_hidden=yes`
|
||||
|
||||
""".format,
|
||||
config_help=CONFIG_HELP.format(conf_name='file-manager', appname=appname),
|
||||
)
|
||||
|
||||
|
||||
def main(args: list[str]) -> None:
|
||||
raise SystemExit('This kitten must be run from a kitty.conf mapping')
|
||||
|
||||
|
||||
def change_directory(w: Any, path: str) -> None:
|
||||
# Writing to the pty, unlike pasting, makes the shell run the command. When
|
||||
# the shell is busy, only paste the text so that it can be edited instead of
|
||||
# feeding it into whatever program is running.
|
||||
cmd = 'cd ' + shlex.quote(path)
|
||||
if w.at_prompt:
|
||||
w.write_to_child(cmd + '\r')
|
||||
else:
|
||||
w.paste_text(cmd)
|
||||
|
||||
|
||||
@result_handler(has_ready_notification=True)
|
||||
def handle_result(args: list[str], data: dict[str, Any], target_window_id: int, boss: BossType) -> None:
|
||||
if not data:
|
||||
return
|
||||
action, path = data.get('action'), data.get('path')
|
||||
if action != 'cd' or not path:
|
||||
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)
|
||||
if w is None:
|
||||
boss.ring_bell_if_allowed()
|
||||
return
|
||||
change_directory(w, path)
|
||||
|
||||
|
||||
help_text = 'Browse directories in a side panel and change the working directory of the shell without leaving it'
|
||||
usage = '[directory]'
|
||||
|
||||
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 directories and change the shell directory'
|
||||
cd['args_completion'] = CompletionSpec.from_string('type:directory')
|
||||
elif __name__ == '__conf__':
|
||||
sys.options_definition = definition # type: ignore
|
||||
@@ -0,0 +1,488 @@
|
||||
// License: GPLv3 Copyright: 2026, FWS
|
||||
|
||||
package file_manager
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/tui/loop"
|
||||
)
|
||||
|
||||
func TestSortEntriesDirectoriesFirstThenByName(t *testing.T) {
|
||||
entries := []Entry{
|
||||
{Name: "zebra.txt"},
|
||||
{Name: "alpha.txt"},
|
||||
{Name: "Beta.txt"},
|
||||
{Name: "zdir", IsDir: true},
|
||||
{Name: "adir", IsDir: true},
|
||||
}
|
||||
sort_entries(entries, "name")
|
||||
expected := []string{"adir", "zdir", "alpha.txt", "Beta.txt", "zebra.txt"}
|
||||
for i, name := range expected {
|
||||
if entries[i].Name != name {
|
||||
t.Fatalf("wrong order at %d: wanted %s got %s", i, name, entries[i].Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSortEntriesByModificationTime(t *testing.T) {
|
||||
entries := []Entry{
|
||||
{Name: "old.txt", ModTime: 10},
|
||||
{Name: "new.txt", ModTime: 30},
|
||||
{Name: "mid.txt", ModTime: 20},
|
||||
{Name: "dir", IsDir: true, ModTime: 1},
|
||||
}
|
||||
sort_entries(entries, "mtime")
|
||||
expected := []string{"dir", "new.txt", "mid.txt", "old.txt"}
|
||||
for i, name := range expected {
|
||||
if entries[i].Name != name {
|
||||
t.Fatalf("wrong order at %d: wanted %s got %s", i, name, entries[i].Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadDirSkipsHiddenFilesUnlessRequested(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
for _, name := range []string{"visible.txt", ".hidden.txt"} {
|
||||
if err := os.WriteFile(filepath.Join(dir, name), nil, 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := os.Mkdir(filepath.Join(dir, "sub"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
entries, err := read_dir(dir, false, "name")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(entries) != 2 {
|
||||
t.Fatalf("wanted 2 entries, got %d: %#v", len(entries), entries)
|
||||
}
|
||||
if !entries[0].IsDir || entries[0].Name != "sub" {
|
||||
t.Fatalf("directories must be listed first, got %#v", entries[0])
|
||||
}
|
||||
|
||||
entries, err = read_dir(dir, true, "name")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(entries) != 3 {
|
||||
t.Fatalf("wanted 3 entries with hidden files shown, got %d", len(entries))
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadDirReportsErrors(t *testing.T) {
|
||||
if _, err := read_dir(filepath.Join(t.TempDir(), "does-not-exist"), false, "name"); err == nil {
|
||||
t.Fatal("reading a missing directory must fail")
|
||||
}
|
||||
}
|
||||
|
||||
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) {
|
||||
for _, name := range []string{"", ".", "..", "a/b", "a\x00b"} {
|
||||
if err := validate_entry_name(name); err == nil {
|
||||
t.Fatalf("%q must be rejected", name)
|
||||
}
|
||||
}
|
||||
for _, name := range []string{"file.txt", "with space", "..hidden"} {
|
||||
if err := validate_entry_name(name); err != nil {
|
||||
t.Fatalf("%q must be accepted, got %v", name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestParentOf(t *testing.T) {
|
||||
cases := map[string]string{
|
||||
"/": "/",
|
||||
"/tmp": "/",
|
||||
"/tmp/a/b": "/tmp/a",
|
||||
"/tmp/a/b/": "/tmp/a/b",
|
||||
}
|
||||
for input, expected := range cases {
|
||||
if got := parent_of(input); got != expected {
|
||||
t.Fatalf("parent_of(%q) = %q, wanted %q", input, got, expected)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateRenameAndDelete(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path, err := create_file(dir, "a.txt")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = os.Stat(path); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = create_file(dir, "a.txt"); err == nil {
|
||||
t.Fatal("creating an existing file must fail")
|
||||
}
|
||||
if _, err = create_subdir(dir, "sub"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
renamed, err := rename_entry(dir, "a.txt", "b.txt")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if filepath.Base(renamed) != "b.txt" {
|
||||
t.Fatalf("unexpected rename destination %q", renamed)
|
||||
}
|
||||
if _, err = os.Stat(filepath.Join(dir, "a.txt")); err == nil {
|
||||
t.Fatal("the old name must no longer exist")
|
||||
}
|
||||
if _, err = rename_entry(dir, "b.txt", "sub"); err == nil {
|
||||
t.Fatal("renaming over an existing entry must fail")
|
||||
}
|
||||
|
||||
if err = delete_entry(dir, "b.txt"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = os.Stat(filepath.Join(dir, "b.txt")); err == nil {
|
||||
t.Fatal("the deleted file must no longer exist")
|
||||
}
|
||||
if err = delete_entry(dir, ".."); err == nil {
|
||||
t.Fatal("deleting the parent directory must be refused")
|
||||
}
|
||||
}
|
||||
|
||||
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) {
|
||||
dir := t.TempDir()
|
||||
file := filepath.Join(dir, "file.txt")
|
||||
if err := os.WriteFile(file, nil, 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := resolve_start_dir(file)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got != dir {
|
||||
t.Fatalf("starting from a file must use its directory, got %q wanted %q", got, dir)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenWithSudoOption(t *testing.T) {
|
||||
c := NewConfig()
|
||||
if c.Open_with_sudo {
|
||||
t.Fatal("files must not be opened with sudo by default")
|
||||
}
|
||||
if err := c.Parse("open_with_sudo", "yes"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !c.Open_with_sudo {
|
||||
t.Fatal("open_with_sudo = yes must enable sudo")
|
||||
}
|
||||
if err := c.Parse("open_with_sudo", "no"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if c.Open_with_sudo {
|
||||
t.Fatal("open_with_sudo = no must disable sudo")
|
||||
}
|
||||
}
|
||||
|
||||
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) {
|
||||
got := edit_args("/tmp/a.py")
|
||||
want := []string{"edit-in-kitty", "--type=tab", "/tmp/a.py"}
|
||||
if len(got) != len(want) {
|
||||
t.Fatalf("expected %#v, got %#v", want, got)
|
||||
}
|
||||
for i := range want {
|
||||
if got[i] != want[i] {
|
||||
t.Fatalf("expected %#v, got %#v", want, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadConfigReadsOpenWithSudo(t *testing.T) {
|
||||
// The option is ignored now, but old configuration files must keep loading.
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "file-manager.conf")
|
||||
if err := os.WriteFile(path, []byte("open_with_sudo yes\neditor nano\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := load_config(&Options{Config: []string{path}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResultPayload(t *testing.T) {
|
||||
h := &Handler{result_action: "cd", result_path: "/tmp"}
|
||||
got := h.result_payload()
|
||||
if len(got) != 2 || got["action"] != "cd" || got["path"] != "/tmp" {
|
||||
t.Fatalf("unexpected payload: %#v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSortEntriesBySize(t *testing.T) {
|
||||
entries := []Entry{
|
||||
{Name: "small.txt", Size: 10},
|
||||
{Name: "large.txt", Size: 300},
|
||||
{Name: "medium.txt", Size: 20},
|
||||
{Name: "dir", IsDir: true, Size: 1},
|
||||
}
|
||||
sort_entries(entries, "size")
|
||||
expected := []string{"dir", "large.txt", "medium.txt", "small.txt"}
|
||||
for i, name := range expected {
|
||||
if entries[i].Name != name {
|
||||
t.Fatalf("wrong order at %d: wanted %s got %s", i, name, entries[i].Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestFilterEntries(t *testing.T) {
|
||||
entries := []Entry{
|
||||
{Name: "alpha.txt"},
|
||||
{Name: "beta.txt"},
|
||||
{Name: "zeta.md"},
|
||||
{Name: "src", IsDir: true},
|
||||
}
|
||||
all, err := filter_entries(entries, "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(all) != len(entries) {
|
||||
t.Fatalf("an empty query must keep every entry, got %#v", all)
|
||||
}
|
||||
|
||||
matches, err := filter_entries(entries, "bt")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(matches) != 1 || matches[0].Name != "beta.txt" {
|
||||
t.Fatalf("unexpected matches for \"bt\": %#v", matches)
|
||||
}
|
||||
|
||||
dirs, err := filter_entries(entries, "src/")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(dirs) != 1 || !dirs[0].IsDir {
|
||||
t.Fatalf("a trailing slash must only match directories, got %#v", dirs)
|
||||
}
|
||||
|
||||
none, err := filter_entries(entries, "zzz")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(none) != 0 {
|
||||
t.Fatalf("a query that matches nothing must return nothing, got %#v", none)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFilterEntriesLargeDirectory(t *testing.T) {
|
||||
entries := make([]Entry, 10_000)
|
||||
for i := range entries {
|
||||
entries[i] = Entry{Name: fmt.Sprintf("file-%05d.txt", i)}
|
||||
}
|
||||
start := time.Now()
|
||||
matches, err := filter_entries(entries, "file-099")
|
||||
elapsed := time.Since(start)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(matches) == 0 {
|
||||
t.Fatal("expected matches in a large directory")
|
||||
}
|
||||
// The bound is deliberately loose: this guards against the filter becoming
|
||||
// superlinear (which turns 10000 entries into seconds), not against a few
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFilterActions(t *testing.T) {
|
||||
all, err := filter_actions("")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(all) != len(action_catalog) {
|
||||
t.Fatalf("an empty query must list the whole catalog, got %d of %d", len(all), len(action_catalog))
|
||||
}
|
||||
matches, err := filter_actions("delete")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(matches) == 0 || matches[0].Name != "delete" {
|
||||
t.Fatalf("the palette must rank the delete action first, got %#v", matches)
|
||||
}
|
||||
}
|
||||
|
||||
func TestActionCatalogMatchesHandlers(t *testing.T) {
|
||||
seen := make(map[string]bool, len(action_catalog))
|
||||
for _, a := range action_catalog {
|
||||
if a.Name == "" || a.Description == "" {
|
||||
t.Fatalf("actions need a name and a description: %#v", a)
|
||||
}
|
||||
if seen[a.Name] {
|
||||
t.Fatalf("duplicate action %q in the catalog", a.Name)
|
||||
}
|
||||
seen[a.Name] = true
|
||||
if _, ok := action_handlers[a.Name]; !ok {
|
||||
t.Fatalf("action %q is described but has no handler", a.Name)
|
||||
}
|
||||
}
|
||||
for name := range action_handlers {
|
||||
if !seen[name] {
|
||||
t.Fatalf("action %q has a handler but no description in the palette", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestEditArgsInWindow(t *testing.T) {
|
||||
got := edit_args_in("/tmp/a.py", "window")
|
||||
want := []string{"edit-in-kitty", "--type=window", "/tmp/a.py"}
|
||||
if len(got) != len(want) {
|
||||
t.Fatalf("expected %#v, got %#v", want, got)
|
||||
}
|
||||
for i := range want {
|
||||
if got[i] != want[i] {
|
||||
t.Fatalf("expected %#v, got %#v", want, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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) {
|
||||
if got := truncate_to_width("abcdef", 3); got != "ab\u2026" {
|
||||
t.Fatalf("unexpected truncation %q", got)
|
||||
}
|
||||
if got := truncate_to_width("abc", 10); got != "abc" {
|
||||
t.Fatalf("short text must not be truncated, got %q", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
// 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())
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
# License: GPLv3 Copyright: 2026, FWS
|
||||
@@ -0,0 +1,47 @@
|
||||
#!/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'
|
||||
@@ -66,6 +66,24 @@ func rune_to_index_map(alphabet string) *map[rune]int {
|
||||
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
|
||||
// the breadth-first traversal of the prefix tree generated by the given
|
||||
// alphabet.
|
||||
|
||||
+110
-24
@@ -7,6 +7,7 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"unicode"
|
||||
@@ -160,6 +161,10 @@ func main(_ *cli.Command, o *Options, args []string) (rc int, err error) {
|
||||
}
|
||||
}
|
||||
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
|
||||
if err != nil {
|
||||
return
|
||||
@@ -168,8 +173,9 @@ func main(_ *cli.Command, o *Options, args []string) (rc int, err error) {
|
||||
faint := fctx.SprintFunc("dim")
|
||||
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))
|
||||
selected_style := fctx.SprintFunc("reverse")
|
||||
|
||||
highlight_mark := func(m *Mark, mark_text string) string {
|
||||
highlight_mark := func(m *Mark, mark_text string, selected bool) string {
|
||||
hint := encode_hint(m.Index, alphabet)
|
||||
if current_input != "" && !strings.HasPrefix(hint, current_input) {
|
||||
return faint(mark_text)
|
||||
@@ -207,6 +213,9 @@ func main(_ *cli.Command, o *Options, args []string) (rc int, err error) {
|
||||
mark_text = string(runes[hint_runes:])
|
||||
}
|
||||
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)
|
||||
}
|
||||
|
||||
@@ -217,7 +226,7 @@ func main(_ *cli.Command, o *Options, args []string) (rc int, err error) {
|
||||
if ignore_mark_indices.Has(mark.Index) {
|
||||
continue
|
||||
}
|
||||
mtext := highlight_mark(mark, ans[mark.Start:mark.End])
|
||||
mtext := highlight_mark(mark, ans[mark.Start:mark.End], pick_from_list && mark.Index == selected_mark)
|
||||
ans = ans[:mark.Start] + mtext + ans[mark.End:]
|
||||
}
|
||||
ans = strings.ReplaceAll(ans, "\x00", "")
|
||||
@@ -238,6 +247,75 @@ func main(_ *cli.Command, o *Options, args []string) (rc int, err error) {
|
||||
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.SetCursorVisible(false)
|
||||
lp.SetWindowTitle(window_title)
|
||||
@@ -295,13 +373,15 @@ func main(_ *cli.Command, o *Options, args []string) (rc int, err error) {
|
||||
}
|
||||
if len(matches) == 1 {
|
||||
chosen = append(chosen, matches[0])
|
||||
if o.Multiple {
|
||||
ignore_mark_indices.Add(matches[0].Index)
|
||||
reset()
|
||||
} else {
|
||||
ignore_mark_indices.Add(matches[0].Index)
|
||||
if !o.Multiple {
|
||||
lp.Quit(0)
|
||||
return nil
|
||||
}
|
||||
reset()
|
||||
}
|
||||
if pick_from_list {
|
||||
select_first()
|
||||
}
|
||||
current_text = ""
|
||||
draw_screen()
|
||||
@@ -310,7 +390,14 @@ func main(_ *cli.Command, o *Options, args []string) (rc int, err error) {
|
||||
}
|
||||
|
||||
lp.OnKeyEvent = func(ev *loop.KeyEvent) error {
|
||||
if ev.MatchesPressOrRepeat("backspace") {
|
||||
if pick_from_list && (ev.MatchesPressOrRepeat("up") || ev.MatchesPressOrRepeat("down")) {
|
||||
ev.Handled = true
|
||||
if ev.MatchesPressOrRepeat("up") {
|
||||
select_by(-1)
|
||||
} else {
|
||||
select_by(1)
|
||||
}
|
||||
} else if ev.MatchesPressOrRepeat("backspace") {
|
||||
ev.Handled = true
|
||||
r := []rune(current_input)
|
||||
if len(r) > 0 {
|
||||
@@ -318,26 +405,25 @@ func main(_ *cli.Command, o *Options, args []string) (rc int, err error) {
|
||||
current_input = string(r)
|
||||
current_text = ""
|
||||
}
|
||||
if pick_from_list {
|
||||
select_first()
|
||||
}
|
||||
draw_screen()
|
||||
} else if ev.MatchesPressOrRepeat("enter") || ev.MatchesPressOrRepeat("space") {
|
||||
} else if ev.MatchesPressOrRepeat("enter") {
|
||||
ev.Handled = true
|
||||
if current_input != "" {
|
||||
char_to_index := rune_to_index_map(alphabet)
|
||||
idx := decode_hint(current_input, char_to_index)
|
||||
if m := index_map[idx]; m != nil {
|
||||
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()
|
||||
if pick_from_list {
|
||||
if selected_mark > -1 {
|
||||
choose_index(selected_mark)
|
||||
} else if marks := visible_marks(); len(marks) > 0 {
|
||||
choose_index(marks[0].Index)
|
||||
}
|
||||
} 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") {
|
||||
if o.Multiple {
|
||||
|
||||
@@ -271,6 +271,14 @@ elsewhere. See {hints_url} for details.
|
||||
--window-title
|
||||
The title for the hints window, default title is based on the type of text being
|
||||
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(
|
||||
default_regex=DEFAULT_REGEX,
|
||||
line='{{line}}',
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
}
|
||||
+96
-1
@@ -40,6 +40,7 @@ from .clipboard import (
|
||||
set_clipboard_string,
|
||||
set_primary_selection,
|
||||
)
|
||||
from .clipboard_history import ClipboardHistory
|
||||
from .colors import ColorSchemes, theme_colors
|
||||
from .conf.utils import BadLine, KeyAction, to_cmdline
|
||||
from .config import common_opts_as_dict, prepare_config_file_for_editing, store_effective_config
|
||||
@@ -419,6 +420,7 @@ class Boss:
|
||||
self.atexit = Atexit()
|
||||
set_layout_options(opts)
|
||||
self.clipboard = Clipboard()
|
||||
self.clipboard_history = ClipboardHistory()
|
||||
self.window_for_dispatch: Window | None = None
|
||||
self.primary_selection = Clipboard(ClipboardType.primary_selection)
|
||||
self.update_check_started = False
|
||||
@@ -2528,6 +2530,7 @@ class Boss:
|
||||
if not self._call_on_quit_watchers({'confirmed': True}):
|
||||
set_application_quit_request(NO_CLOSE_REQUESTED)
|
||||
return
|
||||
self.save_last_session()
|
||||
self.save_session_if_logging_out()
|
||||
set_application_quit_request(IMPERATIVE_CLOSE_REQUESTED)
|
||||
return
|
||||
@@ -2557,9 +2560,20 @@ class Boss:
|
||||
if not self._call_on_quit_watchers({'confirmed': True}):
|
||||
set_application_quit_request(NO_CLOSE_REQUESTED)
|
||||
return
|
||||
self.save_last_session()
|
||||
self.save_session_if_logging_out()
|
||||
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:
|
||||
from .logout_session import is_logout_in_progress
|
||||
|
||||
@@ -2842,6 +2856,15 @@ class Boss:
|
||||
data = collect_keys_data(get_options())
|
||||
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(
|
||||
'tab',
|
||||
"""
|
||||
@@ -3159,6 +3182,68 @@ class Boss:
|
||||
if 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:
|
||||
return get_primary_selection() if supports_primary_selection else ''
|
||||
|
||||
@@ -3700,7 +3785,7 @@ class Boss:
|
||||
final_overrides = old_opts.config_overrides if apply_overrides else ()
|
||||
if overrides:
|
||||
final_overrides += tuple(overrides)
|
||||
opts = load_config(*paths, overrides=final_overrides or None, accumulate_bad_lines=bad_lines)
|
||||
opts = load_config(*paths, overrides=final_overrides or None, accumulate_bad_lines=bad_lines, profile=old_opts.profile_name or None)
|
||||
if bad_lines:
|
||||
self.show_bad_config_lines(bad_lines)
|
||||
from .fonts.render import clear_font_caches
|
||||
@@ -3914,6 +3999,7 @@ class Boss:
|
||||
callback: Callable[[_T | str | None], None],
|
||||
subtitle: str = '',
|
||||
hints_args: tuple[str, ...] | None = None,
|
||||
footer: str = '',
|
||||
) -> Window | None:
|
||||
lines = [title, subtitle, ' '] if subtitle else [title, ' ']
|
||||
idx_map: list[_T | str | None] = []
|
||||
@@ -3926,6 +4012,8 @@ class Boss:
|
||||
lines.append(text)
|
||||
else:
|
||||
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:
|
||||
nonlocal ans
|
||||
@@ -3947,6 +4035,13 @@ class Boss:
|
||||
def goto_session(self, *cmdline: str) -> None:
|
||||
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`.')
|
||||
def save_as_session(self, *cmdline: str) -> None:
|
||||
save_as_session(self, cmdline)
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import termios
|
||||
from collections import defaultdict
|
||||
from collections.abc import Callable, Generator, Iterable, Mapping, Sequence
|
||||
@@ -21,6 +22,20 @@ if TYPE_CHECKING:
|
||||
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:
|
||||
from kitty.fast_data_types import abspath_of_process as _abspath_of_process
|
||||
from kitty.fast_data_types import cmdline_of_process as cmdline_
|
||||
@@ -464,6 +479,7 @@ class Child:
|
||||
elif opts.terminfo_type == 'direct':
|
||||
env['TERMINFO'] = base64_terminfo_data()
|
||||
env['KITTY_INSTALLATION_DIR'] = kitty_base_dir
|
||||
env['KITTY_CWD_SYNC_DIR'] = cwd_sync_dir()
|
||||
self.unmodified_argv = list(self.argv)
|
||||
if not self.should_run_via_run_shell_kitten and 'disabled' not in opts.shell_integration:
|
||||
from .shell_integration import modify_shell_environ
|
||||
|
||||
+1
-1
@@ -737,7 +737,7 @@ def create_opts(args: CLIOptions, accumulate_bad_lines: list[BadLineType] | None
|
||||
|
||||
config = default_config_paths(args.config)
|
||||
overrides = map(parse_override, args.override or ())
|
||||
opts = load_config(*config, overrides=overrides, accumulate_bad_lines=accumulate_bad_lines)
|
||||
opts = load_config(*config, overrides=overrides, accumulate_bad_lines=accumulate_bad_lines, profile=getattr(args, 'profile', ''))
|
||||
return opts
|
||||
|
||||
|
||||
|
||||
+24
-4
@@ -9,6 +9,7 @@ from gettext import gettext as _
|
||||
from tempfile import TemporaryFile
|
||||
from typing import IO, NamedTuple, Union
|
||||
|
||||
from .clipboard_history import text_from_mime_data
|
||||
from .conf.utils import uniq
|
||||
from .constants import supports_primary_selection
|
||||
from .fast_data_types import (
|
||||
@@ -96,15 +97,33 @@ class Clipboard:
|
||||
self.clipboard_type = clipboard_type
|
||||
self.enabled = self.clipboard_type is ClipboardType.clipboard or supports_primary_selection
|
||||
|
||||
def set_text(self, x: str | bytes) -> None:
|
||||
def set_text(self, x: str | bytes, private: bool = False) -> None:
|
||||
if isinstance(x, str):
|
||||
x = x.encode('utf-8')
|
||||
self.set_mime({'text/plain': x})
|
||||
self.set_mime({'text/plain': x}, private=private)
|
||||
|
||||
def set_mime(self, data: Mapping[str, DataType]) -> None:
|
||||
def set_mime(self, data: Mapping[str, DataType], private: bool = False) -> None:
|
||||
if self.enabled and isinstance(data, dict):
|
||||
self.data = dict(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:
|
||||
parts: list[bytes] = []
|
||||
@@ -309,7 +328,8 @@ class WriteRequest:
|
||||
if pos is not None:
|
||||
self.mime_map[alias] = pos
|
||||
x = {mime: self.tempfile.create_chunker(pos.start, pos.size) for mime, pos in self.mime_map.items()}
|
||||
cp.set_mime(x)
|
||||
# A write request that carries a password is private: never keep its data in the history
|
||||
cp.set_mime(x, private=bool(self.password))
|
||||
|
||||
def abort(self, msg: str) -> ValueError:
|
||||
# returns the error to raise, so that callers read as: raise self.abort(...)
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
#!/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)
|
||||
@@ -86,7 +86,7 @@ def generate_class(defn: Definition, loc: str) -> tuple[str, str]:
|
||||
if isinstance(option, MultiOption):
|
||||
mval: dict[str, dict[str, Any]] = {'macos': {}, 'linux': {}, '': {}}
|
||||
func, typ = option_type_data(option)
|
||||
assert isinstance(func, types.FunctionType)
|
||||
assert callable(func), getattr(func, '__name__', func)
|
||||
for val in option:
|
||||
if val.add_to_default:
|
||||
gr = mval[val.only]
|
||||
@@ -115,7 +115,7 @@ def generate_class(defn: Definition, loc: str) -> tuple[str, str]:
|
||||
func = str
|
||||
elif defn.has_color_table and option.is_color_table_color:
|
||||
func, typ = option_type_data(option)
|
||||
assert isinstance(func, types.FunctionType)
|
||||
assert callable(func), getattr(func, '__name__', func)
|
||||
t(f' ans[{option.name!r}] = {func.__name__}(val)')
|
||||
tc_imports.add((func.__module__, func.__name__))
|
||||
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)
|
||||
except Exception:
|
||||
params = {}
|
||||
assert isinstance(func, types.FunctionType)
|
||||
assert callable(func), getattr(func, '__name__', func)
|
||||
if 'dict_with_parse_results' in params:
|
||||
t(f' {func.__name__}(val, ans)')
|
||||
else:
|
||||
@@ -188,7 +188,7 @@ def generate_class(defn: Definition, loc: str) -> tuple[str, str]:
|
||||
for aname, action in defn.actions.items():
|
||||
option_names.add(aname)
|
||||
action_parsers[aname] = func = action.parser_func
|
||||
assert isinstance(func, types.FunctionType)
|
||||
assert callable(func), getattr(func, '__name__', func)
|
||||
th = get_type_hints(func)
|
||||
rettype = th['return']
|
||||
typ = option_type_as_str(rettype)
|
||||
@@ -215,6 +215,7 @@ def generate_class(defn: Definition, loc: str) -> tuple[str, str]:
|
||||
a(' config_paths: tuple[str, ...] = ()')
|
||||
a(' all_config_paths: tuple[str, ...] = ()')
|
||||
a(' config_overrides: tuple[str, ...] = ()')
|
||||
a(" profile_name: str = ''")
|
||||
a('')
|
||||
a(' def __init__(self, options_dict: dict[str, typing.Any] | None = None) -> None:')
|
||||
if defn.has_color_table:
|
||||
|
||||
+95
-3
@@ -245,12 +245,67 @@ def geninclude(path: str) -> list[str]:
|
||||
|
||||
|
||||
include_keys = 'include', 'globinclude', 'envinclude', 'geninclude'
|
||||
profile_start_pat = re.compile(r'^profile\s+([A-Za-z0-9_.-]+)\s*\{$')
|
||||
ProfileLines = list[tuple[str, int, str]]
|
||||
|
||||
|
||||
class RecursiveInclude(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class ProfileCollector:
|
||||
"""Gathers the contents of ``profile <name> { ... }`` blocks instead of parsing them.
|
||||
|
||||
Blocks are buffered so that the caller can parse them separately, after the
|
||||
rest of the configuration, which is what allows a profile to only override
|
||||
the options it declares. One collector is used per file, so a block cannot
|
||||
span an include.
|
||||
"""
|
||||
|
||||
__slots__ = ('profiles', 'current', 'start')
|
||||
|
||||
def __init__(self, profiles: dict[str, ProfileLines]) -> None:
|
||||
self.profiles = profiles
|
||||
self.current: str | None = None
|
||||
self.start: tuple[str, int] = ('', 0)
|
||||
|
||||
def handle(self, line: str, file: str, line_num: int) -> bool:
|
||||
stripped = line.strip()
|
||||
if self.current is None:
|
||||
m = profile_start_pat.match(stripped)
|
||||
if m is not None:
|
||||
self.current = m.group(1)
|
||||
self.start = (file, line_num)
|
||||
self.profiles.setdefault(self.current, [])
|
||||
return True
|
||||
if stripped == '}':
|
||||
raise ValueError('Unexpected "}" outside of a profile block')
|
||||
return False
|
||||
if stripped == '}':
|
||||
self.current = None
|
||||
return True
|
||||
if profile_start_pat.match(stripped) is not None:
|
||||
raise ValueError(f'Profile blocks cannot be nested, found one inside the profile {self.current!r}')
|
||||
self.profiles[self.current].append((file, line_num, line))
|
||||
return True
|
||||
|
||||
def finish(self) -> None:
|
||||
if self.current is not None:
|
||||
file, line_num = self.start
|
||||
where = file or 'the configuration'
|
||||
raise ValueError(f'The profile {self.current!r} opened on line {line_num} of {where} was never closed')
|
||||
|
||||
|
||||
def handle_profile_line(collector: ProfileCollector, line: str, line_num: int, accumulate_bad_lines: list[BadLine] | None) -> bool:
|
||||
try:
|
||||
return collector.handle(line, currently_parsing.file, line_num)
|
||||
except ValueError as e:
|
||||
if accumulate_bad_lines is None:
|
||||
raise
|
||||
accumulate_bad_lines.append(BadLine(line_num, line.rstrip(), e, currently_parsing.file))
|
||||
return True
|
||||
|
||||
|
||||
class Memory:
|
||||
def __init__(self, accumulate_bad_lines: list[BadLine] | None) -> None:
|
||||
self.s: set[str] = set()
|
||||
@@ -283,6 +338,7 @@ def parse_line(
|
||||
memory: Memory,
|
||||
accumulate_bad_lines: list[BadLine] | None = None,
|
||||
allow_geninclude: bool = True,
|
||||
profiles: dict[str, ProfileLines] | None = None,
|
||||
) -> None:
|
||||
line = line.strip()
|
||||
if not line or line.startswith('#'):
|
||||
@@ -312,6 +368,7 @@ def parse_line(
|
||||
accumulate_bad_lines,
|
||||
effective_config_lines,
|
||||
allow_geninclude=allow_geninclude,
|
||||
profiles=profiles,
|
||||
)
|
||||
return
|
||||
elif key == 'geninclude':
|
||||
@@ -338,6 +395,7 @@ def parse_line(
|
||||
accumulate_bad_lines,
|
||||
effective_config_lines,
|
||||
allow_geninclude=allow_geninclude,
|
||||
profiles=profiles,
|
||||
)
|
||||
return
|
||||
else:
|
||||
@@ -350,7 +408,16 @@ def parse_line(
|
||||
try:
|
||||
with open(val, encoding='utf-8', errors='replace') as include:
|
||||
with currently_parsing.set_file(val):
|
||||
_parse(include, parse_conf_item, ans, memory, accumulate_bad_lines, effective_config_lines, allow_geninclude=allow_geninclude)
|
||||
_parse(
|
||||
include,
|
||||
parse_conf_item,
|
||||
ans,
|
||||
memory,
|
||||
accumulate_bad_lines,
|
||||
effective_config_lines,
|
||||
allow_geninclude=allow_geninclude,
|
||||
profiles=profiles,
|
||||
)
|
||||
except FileNotFoundError:
|
||||
log_error(f'Could not find included config file: {val}, ignoring')
|
||||
except OSError:
|
||||
@@ -370,8 +437,10 @@ def _parse(
|
||||
accumulate_bad_lines: list[BadLine] | None = None,
|
||||
effective_config_lines: Callable[[str, str], None] | None = None,
|
||||
allow_geninclude: bool = True,
|
||||
profiles: dict[str, ProfileLines] | None = None,
|
||||
) -> None:
|
||||
name = getattr(lines, 'name', None)
|
||||
collector = ProfileCollector(profiles) if profiles is not None else None
|
||||
effective_config_lines = effective_config_lines or (lambda a, b: None)
|
||||
if name:
|
||||
base_path_for_includes = os.path.abspath(name) if name.endswith(os.path.sep) else os.path.dirname(os.path.abspath(name))
|
||||
@@ -410,7 +479,11 @@ def _parse(
|
||||
next_line = ''
|
||||
try:
|
||||
with currently_parsing.set_line(line, line_num):
|
||||
parse_line(line, parse_conf_item, ans, base_path_for_includes, effective_config_lines, memory, accumulate_bad_lines, allow_geninclude)
|
||||
if collector is not None and handle_profile_line(collector, line, line_num, accumulate_bad_lines):
|
||||
continue
|
||||
parse_line(
|
||||
line, parse_conf_item, ans, base_path_for_includes, effective_config_lines, memory, accumulate_bad_lines, allow_geninclude, profiles
|
||||
)
|
||||
except Exception as e:
|
||||
if accumulate_bad_lines is None:
|
||||
raise
|
||||
@@ -418,6 +491,15 @@ def _parse(
|
||||
except StopIteration:
|
||||
break
|
||||
|
||||
if collector is not None:
|
||||
try:
|
||||
collector.finish()
|
||||
except ValueError as e:
|
||||
if accumulate_bad_lines is None:
|
||||
raise
|
||||
file, line_num = collector.start
|
||||
accumulate_bad_lines.append(BadLine(line_num, '', e, file))
|
||||
|
||||
|
||||
def parse_config_base(
|
||||
lines: Iterable[str],
|
||||
@@ -426,8 +508,18 @@ def parse_config_base(
|
||||
accumulate_bad_lines: list[BadLine] | None = None,
|
||||
effective_config_lines: Callable[[str, str], None] | None = None,
|
||||
allow_geninclude: bool = True,
|
||||
profiles: dict[str, ProfileLines] | None = None,
|
||||
) -> None:
|
||||
_parse(lines, parse_conf_item, ans, Memory(accumulate_bad_lines), accumulate_bad_lines, effective_config_lines, allow_geninclude)
|
||||
_parse(
|
||||
lines,
|
||||
parse_conf_item,
|
||||
ans,
|
||||
Memory(accumulate_bad_lines),
|
||||
accumulate_bad_lines,
|
||||
effective_config_lines,
|
||||
allow_geninclude,
|
||||
profiles=profiles,
|
||||
)
|
||||
|
||||
|
||||
def merge_dicts(defaults: dict[str, Any], newvals: dict[str, Any]) -> dict[str, Any]:
|
||||
|
||||
+104
-4
@@ -3,12 +3,12 @@
|
||||
|
||||
import json
|
||||
import os
|
||||
from collections.abc import Callable, Generator, Iterable
|
||||
from collections.abc import Callable, Generator, Iterable, Iterator, Sequence
|
||||
from contextlib import contextmanager, suppress
|
||||
from functools import partial
|
||||
from typing import Any
|
||||
|
||||
from .conf.utils import BadLine, parse_config_base
|
||||
from .conf.utils import BadLine, NamedLineIterator, ProfileLines, currently_parsing, parse_config_base
|
||||
from .conf.utils import load_config as _load_config
|
||||
from .constants import cache_dir, defconf
|
||||
from .options.types import Options, defaults, option_names
|
||||
@@ -80,6 +80,45 @@ def prepare_config_file_for_editing() -> str:
|
||||
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:
|
||||
defns: list[KeyDefinition] = []
|
||||
for d in opts.map:
|
||||
@@ -118,6 +157,7 @@ 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.append(defn)
|
||||
opts.keyboard_modes = modes
|
||||
finalize_leader(opts)
|
||||
|
||||
|
||||
def finalize_mouse_mappings(opts: Options, accumulate_bad_lines: list[BadLine] | None = None) -> None:
|
||||
@@ -162,6 +202,7 @@ def parse_config(
|
||||
accumulate_bad_lines: list[BadLine] | None = None,
|
||||
effective_config_lines: Callable[[str, str], None] | None = None,
|
||||
allow_geninclude: bool = True,
|
||||
profiles: dict[str, ProfileLines] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
from .options.parse import create_result_dict, parse_conf_item
|
||||
|
||||
@@ -173,14 +214,62 @@ def parse_config(
|
||||
accumulate_bad_lines=accumulate_bad_lines,
|
||||
effective_config_lines=effective_config_lines,
|
||||
allow_geninclude=allow_geninclude,
|
||||
profiles=profiles,
|
||||
)
|
||||
return ans
|
||||
|
||||
|
||||
def resolve_profile_name(profile: str | None = None) -> str:
|
||||
"""The explicitly requested profile wins over the environment variable."""
|
||||
ans = profile if profile else os.environ.get('KITTY_PROFILE', '')
|
||||
return ans.strip()
|
||||
|
||||
|
||||
def _lines_by_file(lines: Sequence[tuple[str, int, str]]) -> Iterator[tuple[str, list[str]]]:
|
||||
"""Group consecutive lines read from the same file, padding them so that
|
||||
their line numbers stay the ones of the original configuration file."""
|
||||
group: list[str] = []
|
||||
current = ''
|
||||
for file, line_num, line in lines:
|
||||
if group and file != current:
|
||||
yield current, group
|
||||
group = []
|
||||
current = file
|
||||
while len(group) < line_num - 1:
|
||||
group.append('')
|
||||
group.append(line)
|
||||
if group:
|
||||
yield current, group
|
||||
|
||||
|
||||
def parse_profile_lines(
|
||||
lines: Sequence[tuple[str, int, str]],
|
||||
accumulate_bad_lines: list[BadLine] | None = None,
|
||||
effective_config_lines: Callable[[str, str], None] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
from .options.parse import actions, create_result_dict
|
||||
|
||||
ans = create_result_dict()
|
||||
for file, group in _lines_by_file(lines):
|
||||
# Lines read from STDIN or from the command line have no directory to
|
||||
# resolve includes against, so let the parser fall back to config_dir.
|
||||
name = file if file and file != '-' and not file.startswith('<') else ''
|
||||
with currently_parsing.set_file(name):
|
||||
vals = parse_config(NamedLineIterator(name, iter(group)), accumulate_bad_lines=accumulate_bad_lines, effective_config_lines=effective_config_lines)
|
||||
for k, v in vals.items():
|
||||
if isinstance(v, dict):
|
||||
ans.setdefault(k, {}).update(v)
|
||||
elif k in actions:
|
||||
ans.setdefault(k, []).extend(v)
|
||||
else:
|
||||
ans[k] = v
|
||||
return ans
|
||||
|
||||
|
||||
effective_config_lines: list[str] = []
|
||||
|
||||
|
||||
def load_config(*paths: str, overrides: Iterable[str] | None = None, accumulate_bad_lines: list[BadLine] | None = None) -> Options:
|
||||
def load_config(*paths: str, overrides: Iterable[str] | None = None, accumulate_bad_lines: list[BadLine] | None = None, profile: str | None = None) -> Options:
|
||||
from .options.parse import merge_result_dicts
|
||||
from .options.types import secret_options
|
||||
|
||||
@@ -191,14 +280,24 @@ def load_config(*paths: str, overrides: Iterable[str] | None = None, accumulate_
|
||||
effective_config_lines.append(line)
|
||||
|
||||
overrides = tuple(overrides) if overrides is not None else ()
|
||||
profiles: dict[str, ProfileLines] = {}
|
||||
|
||||
opts_dict, found_paths = _load_config(
|
||||
defaults,
|
||||
partial(parse_config, accumulate_bad_lines=accumulate_bad_lines, effective_config_lines=add_effective_config_line),
|
||||
partial(parse_config, accumulate_bad_lines=accumulate_bad_lines, effective_config_lines=add_effective_config_line, profiles=profiles),
|
||||
merge_result_dicts,
|
||||
*paths,
|
||||
overrides=overrides,
|
||||
)
|
||||
active_profile = resolve_profile_name(profile)
|
||||
if active_profile:
|
||||
profile_lines = profiles.get(active_profile)
|
||||
if profile_lines is None:
|
||||
log_error(f'The configuration profile {active_profile!r} is not defined, ignoring it')
|
||||
else:
|
||||
# Parsed after the global configuration so that it is layered on top
|
||||
# of it and only needs to list the options it changes.
|
||||
opts_dict = merge_result_dicts(opts_dict, parse_profile_lines(profile_lines, accumulate_bad_lines, add_effective_config_line))
|
||||
opts = Options(opts_dict)
|
||||
|
||||
opts.alias_map = build_action_aliases(opts.kitten_alias, 'kitten')
|
||||
@@ -213,6 +312,7 @@ def load_config(*paths: str, overrides: Iterable[str] | None = None, accumulate_
|
||||
opts.config_paths = found_paths
|
||||
opts.all_config_paths = paths
|
||||
opts.config_overrides = overrides
|
||||
opts.profile_name = active_profile
|
||||
return opts
|
||||
|
||||
|
||||
|
||||
+32
-1
@@ -23,7 +23,7 @@ from .fast_data_types import (
|
||||
set_ignore_os_keyboard_processing,
|
||||
)
|
||||
from .options.types import Options
|
||||
from .options.utils import KeyboardMode, KeyDefinition, KeyFallbackType, KeyMap, KeyMapOptions
|
||||
from .options.utils import KeyboardMode, KeyDefinition, KeyFallbackType, KeyMap, KeyMapOptions, parse_shortcut
|
||||
from .typing_compat import ScreenType
|
||||
|
||||
if TYPE_CHECKING:
|
||||
@@ -40,6 +40,14 @@ def keyboard_mode_name(screen: ScreenType) -> str:
|
||||
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:
|
||||
mods = ev.mods & mod_mask
|
||||
ans = keymap.get(SingleKey(mods, False, ev.key))
|
||||
@@ -111,6 +119,24 @@ class Mappings:
|
||||
self.keyboard_modes[''].keymap = km = km.copy()
|
||||
for sc in self.global_shortcuts.values():
|
||||
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:
|
||||
had_mode = bool(self.keyboard_mode_stack)
|
||||
@@ -212,6 +238,11 @@ class Mappings:
|
||||
# Handles shortcuts, return True if the key was consumed
|
||||
is_root_mode = not self.keyboard_mode_stack
|
||||
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)
|
||||
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):
|
||||
|
||||
@@ -424,8 +424,10 @@ handle_fast_commandline(CLISpec *cli_spec, const char *instance_group_prefix) {
|
||||
if (get_bool_cli_val(cli_spec, "version")) {
|
||||
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[3mfws-kitty\x1b[23m \x1b[32m0.1.17\x1b[39m by \x1b[1;34mBlackAngelTV\x1b[22;39m\n");
|
||||
} else {
|
||||
printf("kitty %s created by Kovid Goyal\n", KITTY_VERSION);
|
||||
printf("fws-kitty 0.1.17 by BlackAngelTV\n");
|
||||
}
|
||||
exit(0);
|
||||
}
|
||||
|
||||
@@ -68,6 +68,7 @@ from .options.types import Options
|
||||
from .options.utils import DELETE_ENV_VAR
|
||||
from .os_window_size import edge_spacing, initial_window_size_func
|
||||
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 .types import LayerShellConfig
|
||||
from .utils import (
|
||||
@@ -394,6 +395,8 @@ def _run_app(opts: Options, args: CLIOptions, bad_lines: Sequence[BadLine] = (),
|
||||
try:
|
||||
boss.child_monitor.main_loop()
|
||||
finally:
|
||||
if not _is_panel_kitten:
|
||||
save_session_of(boss)
|
||||
boss.destroy()
|
||||
|
||||
|
||||
|
||||
+19
-1
@@ -2,7 +2,7 @@
|
||||
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
import re
|
||||
from collections.abc import Callable, Generator, Iterable, Sequence
|
||||
from collections.abc import Callable, Generator, Iterable, Mapping, Sequence
|
||||
from re import Pattern
|
||||
from typing import Union
|
||||
|
||||
@@ -29,6 +29,24 @@ def marker_from_regex(expression: Union[str, 'Pattern[str]'], color: int, flags:
|
||||
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:
|
||||
expr = ''
|
||||
color_map = {}
|
||||
|
||||
@@ -2183,6 +2183,73 @@ update_mock_pointer(PyObject *self UNUSED, PyObject *args) {
|
||||
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 *
|
||||
test_scale_scroll(PyObject *self UNUSED, PyObject *args) {
|
||||
PyObject *values;
|
||||
@@ -2258,6 +2325,7 @@ static PyMethodDef module_methods[] = {
|
||||
METHODB(test_mapped_scroll_steps, METH_VARARGS),
|
||||
METHODB(send_mock_mouse_event_to_window, 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(mock_mouse_selection, METH_VARARGS),
|
||||
{NULL, NULL, 0, NULL} /* Sentinel */
|
||||
|
||||
+108
-12
@@ -2318,18 +2318,18 @@ The alignment of the tab bar, can be one of: :code:`start`, :code:`center`,
|
||||
|
||||
opt(
|
||||
'tab_bar_show_new_tab_button',
|
||||
'no',
|
||||
'yes',
|
||||
option_type='to_bool',
|
||||
long_text="""
|
||||
When set to :code:`yes`, a :code:`+` button is always shown at the end of the
|
||||
tab bar as a clickable shortcut to open a new tab. When set to :code:`no`
|
||||
(the default), the button is hidden at rest but still appears temporarily
|
||||
while a window is being dragged, so it can be used as a drop target to open
|
||||
the window in a new tab.
|
||||
When set to :code:`yes` (the default), a :code:`+` button is always shown at
|
||||
the end of the tab bar as a clickable shortcut to open a new tab. When set to
|
||||
:code:`no`, the button is hidden at rest but still appears temporarily while a
|
||||
window is being dragged, so it can be used as a drop target to open the window
|
||||
in a new tab.
|
||||
""",
|
||||
)
|
||||
|
||||
opt('tab_bar_min_tabs', '2', option_type='tab_bar_min_tabs', long_text='The minimum number of tabs that must exist before the tab bar is shown.')
|
||||
opt('tab_bar_min_tabs', '1', option_type='tab_bar_min_tabs', long_text='The minimum number of tabs that must exist before the tab bar is shown.')
|
||||
|
||||
opt(
|
||||
'tab_switch_strategy',
|
||||
@@ -2450,7 +2450,8 @@ lines is wrapped independently.
|
||||
|
||||
opt(
|
||||
'tab_title_template',
|
||||
'"{fmt.fg.red}{bell_symbol}{activity_symbol}{secure_input_symbol}{fmt.fg.tab}{tab.last_focused_progress_percent}{title}"',
|
||||
'"{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}"',
|
||||
option_type='tab_title_template',
|
||||
long_text="""
|
||||
A template to render the tab title. The default just renders the title with
|
||||
@@ -2473,12 +2474,25 @@ use :code:`{sup.index}`. All data available is:
|
||||
The number of windows in the tab.
|
||||
:code:`num_window_groups`
|
||||
The number of window groups (a window group is a window and all of its overlay windows) in the tab.
|
||||
:code:`last_exit_code`
|
||||
The exit status of the last command that finished in the active window of
|
||||
the tab, or the empty string if it succeeded or no command has finished.
|
||||
Requires :ref:`shell integration <shell_integration>`.
|
||||
:code:`exit_status_symbol`
|
||||
A cross followed by :code:`last_exit_code` when the last command failed,
|
||||
empty otherwise. Requires :ref:`shell integration <shell_integration>`.
|
||||
:code:`secure_input_symbol`
|
||||
A key symbol when secure input is enabled on macOS and the tab is the active tab, empty otherwise.
|
||||
:code:`tab.active_wd`
|
||||
The working directory of the currently active window in the tab
|
||||
(expensive, requires syscall). Use :code:`tab.active_oldest_wd` to get
|
||||
the directory of the oldest foreground process rather than the newest.
|
||||
:code:`tab.active_wd_abbreviated`
|
||||
A compact form of :code:`tab.active_wd` suited to a tab title: the home
|
||||
directory is shown as ``~``, intermediate directories are reduced to
|
||||
their first letter and, when the result is still too long, middle
|
||||
directories are replaced by an ellipsis. For example
|
||||
``~/p/fws-kitty``. Has the same cost as :code:`tab.active_wd`.
|
||||
:code:`tab.active_exe`
|
||||
The name of the executable running in the foreground of the currently
|
||||
active window in the tab (expensive, requires syscall). Use
|
||||
@@ -2518,9 +2532,9 @@ use styling directives, for example:
|
||||
Similarly, for bold and italic:
|
||||
``{fmt.bold}bold{fmt.nobold}normal{fmt.italic}italic{fmt.noitalic}``.
|
||||
The 256 eight terminal colors can be used as ``fmt.fg.color0`` through ``fmt.fg.color255``.
|
||||
Note that for backward compatibility, if :code:`{bell_symbol}` or
|
||||
:code:`{activity_symbol}` are not present in the template, they are prepended to
|
||||
it.
|
||||
Note that for backward compatibility, if :code:`{bell_symbol}`,
|
||||
:code:`{activity_symbol}` or :code:`{exit_status_symbol}` are not present in
|
||||
the template, they are prepended to it.
|
||||
""",
|
||||
)
|
||||
|
||||
@@ -3342,11 +3356,14 @@ first valid match, in the order specified, is sourced.
|
||||
|
||||
opt(
|
||||
'notify_on_cmd_finish',
|
||||
'never',
|
||||
'unfocused',
|
||||
option_type='notify_on_cmd_finish',
|
||||
long_text="""
|
||||
Show a desktop notification when a long-running command finishes
|
||||
(needs :opt:`shell_integration`).
|
||||
The notification gives the command line, how long it ran and its exit status.
|
||||
By default commands running longer than 5 seconds are reported when the window
|
||||
loses focus, set the value to :code:`never` to disable this.
|
||||
The possible values are:
|
||||
|
||||
:code:`never`
|
||||
@@ -3774,6 +3791,22 @@ 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(
|
||||
'remap_modifiers',
|
||||
'',
|
||||
@@ -3943,6 +3976,15 @@ map(
|
||||
'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(
|
||||
'Pass selection to program',
|
||||
'pass_selection_to_program --allow-fallback=shifted,ascii kitty_mod+o pass_selection_to_program',
|
||||
@@ -4115,6 +4157,22 @@ 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 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() # }}}
|
||||
|
||||
@@ -4636,6 +4694,23 @@ 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 {{{
|
||||
agr('shortcuts.misc', 'Miscellaneous')
|
||||
|
||||
@@ -4643,6 +4718,27 @@ map('Show documentation', 'show_kitty_doc kitty_mod+f1 show_kitty_doc overview')
|
||||
|
||||
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(
|
||||
'File manager',
|
||||
'file_manager ctrl+shift+e launch --type=window-dock --dock-edge=left --dock-size=60 kitten file-manager',
|
||||
long_text="""
|
||||
Open the built-in file manager in a dock at the left edge of the current window.
|
||||
It can also be launched manually with :code:`kitten file-manager`.
|
||||
""",
|
||||
)
|
||||
|
||||
map(
|
||||
'Toggle fullscreen',
|
||||
'toggle_fullscreen kitty_mod+f11 toggle_fullscreen',
|
||||
|
||||
Generated
+3
@@ -1094,6 +1094,9 @@ class Parser:
|
||||
def kitty_mod(self, val: str, ans: dict[str, typing.Any]) -> None:
|
||||
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:
|
||||
ans['linux_bell_theme'] = str(val)
|
||||
|
||||
|
||||
Generated
+1
@@ -4,6 +4,7 @@
|
||||
#include "to-c.h"
|
||||
|
||||
|
||||
|
||||
static void
|
||||
convert_from_python_font_size(PyObject *val, Options *opts) {
|
||||
opts->font_size = PyFloat_AsDouble(val);
|
||||
|
||||
Generated
+19
-4
@@ -388,6 +388,7 @@ option_names = (
|
||||
'italic_font',
|
||||
'kitten_alias',
|
||||
'kitty_mod',
|
||||
'leader',
|
||||
'linux_bell_theme',
|
||||
'linux_display_server',
|
||||
'listen_on',
|
||||
@@ -613,6 +614,7 @@ class Options:
|
||||
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')
|
||||
kitty_mod: int = 5
|
||||
leader: str = 'ctrl+space'
|
||||
linux_bell_theme: str = '__custom'
|
||||
linux_display_server: choices_for_linux_display_server = 'auto'
|
||||
listen_on: str = 'none'
|
||||
@@ -640,7 +642,7 @@ class Options:
|
||||
mark3_foreground: Color = Color(0, 0, 0)
|
||||
momentum_scroll: float = 0.96
|
||||
mouse_hide_wait: MouseHideWait = MouseHideWait(hide_wait=0.0, show_wait=0.0, show_threshold=40, scroll_show=True) if is_macos else MouseHideWait(hide_wait=3.0, show_wait=0.0, show_threshold=40, scroll_show=True)
|
||||
notify_on_cmd_finish: NotifyOnCmdFinish = NotifyOnCmdFinish(when='never', duration=5.0, action='notify', cmdline=(), clear_on=('focus', 'next'))
|
||||
notify_on_cmd_finish: NotifyOnCmdFinish = NotifyOnCmdFinish(when='unfocused', duration=5.0, action='notify', cmdline=(), clear_on=('focus', 'next'))
|
||||
open_url_with: list[str] = ['default']
|
||||
padding_fill_strategy: choices_for_padding_fill_strategy = 'background'
|
||||
palette_generate: choices_for_palette_generate = 'fixed'
|
||||
@@ -695,8 +697,8 @@ class Options:
|
||||
tab_bar_margin_color: kitty.fast_data_types.Color | None = None
|
||||
tab_bar_margin_height: TabBarMarginHeight = TabBarMarginHeight(outer=0, inner=0)
|
||||
tab_bar_margin_width: float = 0
|
||||
tab_bar_min_tabs: int = 2
|
||||
tab_bar_show_new_tab_button: bool = False
|
||||
tab_bar_min_tabs: int = 1
|
||||
tab_bar_show_new_tab_button: bool = True
|
||||
tab_bar_style: choices_for_tab_bar_style = 'fade'
|
||||
tab_fade: tuple[float, ...] = (0.25, 0.5, 0.75, 1.0)
|
||||
tab_powerline_style: choices_for_tab_powerline_style = 'angled'
|
||||
@@ -704,7 +706,7 @@ class Options:
|
||||
tab_switch_strategy: choices_for_tab_switch_strategy = 'previous'
|
||||
tab_title_max_length: int = 0
|
||||
tab_title_max_lines: int = 1
|
||||
tab_title_template: str = '{fmt.fg.red}{bell_symbol}{activity_symbol}{secure_input_symbol}{fmt.fg.tab}{tab.last_focused_progress_percent}{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}{tab.active_wd_abbreviated} {title}'
|
||||
tab_title_wrap: int = 0
|
||||
term: str = 'xterm-kitty'
|
||||
terminfo_type: choices_for_terminfo_type = 'path'
|
||||
@@ -803,6 +805,7 @@ class Options:
|
||||
config_paths: tuple[str, ...] = ()
|
||||
all_config_paths: tuple[str, ...] = ()
|
||||
config_overrides: tuple[str, ...] = ()
|
||||
profile_name: str = ''
|
||||
|
||||
def __init__(self, options_dict: dict[str, typing.Any] | None = None) -> None:
|
||||
self.color_table = array(self.color_table.typecode, self.color_table)
|
||||
@@ -901,6 +904,10 @@ 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'),
|
||||
# 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
|
||||
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
|
||||
@@ -929,6 +936,8 @@ 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'),
|
||||
# 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
|
||||
KeyDefinition(trigger=SingleKey(mods=256, key=57345), definition='new_window'),
|
||||
# new_os_window
|
||||
@@ -1023,10 +1032,16 @@ 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'),
|
||||
# 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'),
|
||||
# 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
|
||||
KeyDefinition(trigger=SingleKey(mods=256, key=57364), definition='show_kitty_doc overview'),
|
||||
# command_palette
|
||||
KeyDefinition(trigger=SingleKey(mods=256, key=57366), definition='command_palette'),
|
||||
# file_manager
|
||||
KeyDefinition(trigger=SingleKey(mods=5, key=101), definition='launch --type=window-dock --dock-edge=left --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
|
||||
KeyDefinition(trigger=SingleKey(mods=256, key=57374), definition='toggle_fullscreen'),
|
||||
# toggle_maximized
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
#!/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))
|
||||
+9
-1
@@ -327,7 +327,15 @@ def create_sessions(
|
||||
env_when_no_session: dict[str, str] | None = None,
|
||||
) -> Iterator[Session]:
|
||||
if args and args.session:
|
||||
if args.session == 'none':
|
||||
if args.session == 'last':
|
||||
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'
|
||||
else:
|
||||
session_arg = args.session
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
#!/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
|
||||
@@ -416,6 +416,13 @@ completion=type:file ext:conf group:"Config files" kwds:none,NONE
|
||||
{config_help}
|
||||
|
||||
|
||||
--profile
|
||||
Apply the named configuration profile on top of the loaded configuration.
|
||||
Profiles are declared in :file:`kitty.conf` with
|
||||
:code:`profile <name> {{ ... }}` blocks. This overrides the
|
||||
:envvar:`KITTY_PROFILE` environment variable.
|
||||
|
||||
|
||||
--override -o
|
||||
type=list
|
||||
completion=type:special group:complete_kitty_override
|
||||
|
||||
+101
-3
@@ -260,6 +260,17 @@ class TabAccessor:
|
||||
tab = get_boss().tab_for_id(self.tab_id)
|
||||
return os.path.basename((tab.get_exe_of_active_window(oldest=True) if tab else '') or '')
|
||||
|
||||
@property
|
||||
def active_wd_abbreviated(self) -> str:
|
||||
tab = get_boss().tab_for_id(self.tab_id)
|
||||
return abbreviate_path((tab.get_cwd_of_active_window() if tab else '') or '')
|
||||
|
||||
@property
|
||||
def last_cmd_exit_status(self) -> int:
|
||||
tab = get_boss().tab_for_id(self.tab_id)
|
||||
w = tab.active_window if tab else None
|
||||
return w.last_cmd_exit_status if w else 0
|
||||
|
||||
@property
|
||||
def last_focused_progress_percent(self) -> str:
|
||||
tab = get_boss().tab_for_id(self.tab_id)
|
||||
@@ -337,6 +348,10 @@ def template_uses_max_title_length(template: str) -> bool:
|
||||
# Not across updates, as templates can use state not in TabBarData, such as
|
||||
# the progress of the windows in the tab.
|
||||
title_cache: dict[tuple[DrawData, TabBarData, int, int], str] | None = None
|
||||
# Cells occupied by the close buttons drawn in the last layout pass, mapped to
|
||||
# the id of the tab they close. None while titles are being measured, so that
|
||||
# only the cells of the final drawing are kept.
|
||||
close_button_cells: dict[tuple[int, int], int] | None = None
|
||||
|
||||
|
||||
@contextmanager
|
||||
@@ -384,6 +399,7 @@ def evaluate_title_template(draw_data: DrawData, tab: TabBarData, index: int, ma
|
||||
ColorFormatter.draw_data = draw_data
|
||||
ColorFormatter.tab_data = tab
|
||||
boss = get_boss()
|
||||
last_cmd_exit_status = ta.last_cmd_exit_status
|
||||
eval_locals = {
|
||||
'index': index,
|
||||
'layout_name': tab.layout_name,
|
||||
@@ -400,6 +416,8 @@ def evaluate_title_template(draw_data: DrawData, tab: TabBarData, index: int, ma
|
||||
'bell_symbol': draw_data.bell_on_tab if tab.needs_attention else '',
|
||||
'secure_input_symbol': si,
|
||||
'activity_symbol': draw_data.tab_activity_symbol if tab.has_activity_since_last_focus else '',
|
||||
'last_exit_code': str(last_cmd_exit_status) if last_cmd_exit_status else '',
|
||||
'exit_status_symbol': exit_status_indicator(last_cmd_exit_status),
|
||||
'max_title_length': max_title_length,
|
||||
'keyboard_mode': boss.mappings.current_keyboard_mode_name,
|
||||
}
|
||||
@@ -407,7 +425,7 @@ def evaluate_title_template(draw_data: DrawData, tab: TabBarData, index: int, ma
|
||||
if tab.is_active and draw_data.active_title_template is not None:
|
||||
template = draw_data.active_title_template
|
||||
prefix = ''
|
||||
for default_prefix in ('bell_symbol', 'activity_symbol', 'secure_input_symbol'):
|
||||
for default_prefix in ('bell_symbol', 'activity_symbol', 'exit_status_symbol', 'secure_input_symbol'):
|
||||
if eval_locals[default_prefix] and not template_has_field(template, default_prefix):
|
||||
prefix += '{' + default_prefix + '}'
|
||||
if prefix:
|
||||
@@ -498,8 +516,65 @@ def truncate_line(line: str, width: int) -> str:
|
||||
return out + '…'
|
||||
|
||||
|
||||
def exit_status_indicator(exit_status: int) -> str:
|
||||
"""A short indicator for the exit status of the last command, empty on success."""
|
||||
return f'✘ {exit_status} ' if exit_status else ''
|
||||
|
||||
|
||||
def abbreviate_path(path: str, home: str | None = None, max_length: int = 0) -> str:
|
||||
"""Return a compact representation of path for use in a tab title.
|
||||
|
||||
The home directory is shown as ``~`` and the directories between it and
|
||||
the last component are reduced to their first character, so
|
||||
``~/projects/fws-kitty`` becomes ``~/p/fws-kitty``. When max_length is
|
||||
positive and the result is wider, the middle directories are replaced by
|
||||
an ellipsis, keeping the last component, which is the most informative
|
||||
part. Widths are measured in terminal cells.
|
||||
"""
|
||||
if not path:
|
||||
return ''
|
||||
home = os.path.normpath(home or os.path.expanduser('~'))
|
||||
p = os.path.normpath(path)
|
||||
if home and (p == home or p.startswith(home + os.sep)):
|
||||
prefix, rest = '~', p[len(home) :]
|
||||
elif p.startswith(os.sep):
|
||||
prefix, rest = os.sep, p
|
||||
else:
|
||||
prefix, rest = '', p
|
||||
components = [c for c in rest.split(os.sep) if c]
|
||||
if not components:
|
||||
return prefix or os.sep
|
||||
|
||||
def join(parts: Sequence[str]) -> str:
|
||||
if prefix == os.sep:
|
||||
return os.sep + os.sep.join(parts)
|
||||
if prefix == '~':
|
||||
return '~' + (os.sep + os.sep.join(parts) if parts else '')
|
||||
return os.sep.join(parts)
|
||||
|
||||
ans = join([c[0] for c in components[:-1]] + [components[-1]])
|
||||
if max_length > 0 and wcswidth(ans) > max_length:
|
||||
last = components[-1]
|
||||
marker = prefix + os.sep + '…' if prefix else '…'
|
||||
for candidate in (marker + os.sep + last, '…' + os.sep + last if prefix else last):
|
||||
if wcswidth(candidate) <= max_length:
|
||||
return candidate
|
||||
# Even the last component alone is too wide, keep its end as that is
|
||||
# the part that distinguishes it from its siblings.
|
||||
available = max_length - wcswidth(marker) - 1
|
||||
if available > 0:
|
||||
return marker + os.sep + truncate_line(last, available)
|
||||
return truncate_line(ans, max_length)
|
||||
return ans
|
||||
|
||||
|
||||
def draw_title(draw_data: DrawData, screen: Screen, tab: TabBarData, index: int, max_title_length: int = 0) -> None:
|
||||
title = apply_title_template(draw_data, tab, index, max_title_length)
|
||||
# Close buttons live in horizontal tab bars, where there is a spare cell at
|
||||
# the start of each tab. Vertical tabs are already crowded and their titles
|
||||
# wrap, so they keep closing with the middle mouse button.
|
||||
show_close = tab.tab_id > 0 and draw_data.tab_bar_edge in ('top', 'bottom') and (max_title_length <= 0 or max_title_length >= 3)
|
||||
title_width = max(1, max_title_length - 2) if show_close and max_title_length > 0 else max_title_length
|
||||
title = apply_title_template(draw_data, tab, index, title_width)
|
||||
if draw_data.max_tab_title_lines > 1 and draw_data.wrap_width:
|
||||
title = wrap_title(title, draw_data.wrap_width)
|
||||
if '\n' in title:
|
||||
@@ -511,9 +586,14 @@ def draw_title(draw_data: DrawData, screen: Screen, tab: TabBarData, index: int,
|
||||
# Mark the truncation, since the caller's ellipsis logic only fires
|
||||
# when the final line reaches the full width of the tab.
|
||||
del lines[limit:]
|
||||
lines[-1] = truncate_line(lines[-1], draw_data.wrap_width or max_title_length)
|
||||
lines[-1] = truncate_line(lines[-1], draw_data.wrap_width or title_width)
|
||||
title = '\n'.join(lines)
|
||||
before_draw = screen.cursor.x
|
||||
if show_close:
|
||||
if close_button_cells is not None:
|
||||
close_button_cells[(before_draw, screen.cursor.y)] = tab.tab_id
|
||||
close_button_cells[(before_draw + 1, screen.cursor.y)] = tab.tab_id
|
||||
screen.draw('× ')
|
||||
draw_attributed_string(title, screen)
|
||||
if draw_data.max_tab_title_length > 0:
|
||||
x_limit = before_draw + draw_data.max_tab_title_length
|
||||
@@ -811,6 +891,7 @@ class TabBar:
|
||||
self.data_buffer_size = 0
|
||||
self.blank_rects: tuple[Border, ...] = ()
|
||||
self.tab_extents: Sequence[TabExtent] = ()
|
||||
self.close_button_cells: dict[tuple[int, int], int] = {}
|
||||
self.window_drop_insert_before: int | None = None
|
||||
self.tab_drop_insert_before: int | None = None
|
||||
self.laid_out_once = False
|
||||
@@ -996,6 +1077,7 @@ class TabBar:
|
||||
self.blank_rects = tuple(blank_rects)
|
||||
|
||||
def layout(self) -> None:
|
||||
self.close_button_cells = {}
|
||||
central, tab_bar, vw, vh, cell_width, cell_height = viewport_for_window(self.os_window_id)
|
||||
if self.is_vertical:
|
||||
if tab_bar.width < cell_width or tab_bar.height < cell_height:
|
||||
@@ -1149,11 +1231,15 @@ class TabBar:
|
||||
s.erase_in_line(2, False)
|
||||
cr: list[TabExtent] = []
|
||||
ed.for_layout = False
|
||||
global close_button_cells
|
||||
close_button_cells = {}
|
||||
for i, t in enumerate(data):
|
||||
try:
|
||||
draw_tab(i, t, cr, max_tab_lengths[i])
|
||||
except StopIteration:
|
||||
break
|
||||
self.close_button_cells = close_button_cells
|
||||
close_button_cells = None
|
||||
self.tab_extents = cr
|
||||
s.erase_in_line(0, False) # Ensure no long titles bleed after the last tab
|
||||
self.align()
|
||||
@@ -1164,6 +1250,7 @@ class TabBar:
|
||||
s = self.screen
|
||||
self.last_laid_out_tabs = data
|
||||
self.tab_extents = ()
|
||||
self.close_button_cells = {}
|
||||
s.cursor.x = s.cursor.y = 0
|
||||
s.erase_in_display(2, False)
|
||||
if not data:
|
||||
@@ -1312,6 +1399,17 @@ class TabBar:
|
||||
return te.tab_id
|
||||
return 0
|
||||
|
||||
def close_tab_id_at(self, x: int, y: int) -> int:
|
||||
"The id of the tab whose close button is at the specified pixel, or zero."
|
||||
if not self.laid_out_once or not self.close_button_cells:
|
||||
return 0
|
||||
g = self.window_geometry
|
||||
if not (g.left <= x < g.right and g.top <= y < g.bottom):
|
||||
return 0
|
||||
x = (x - g.left) // self.cell_width
|
||||
y = (y - g.top) // self.cell_height
|
||||
return self.close_button_cells.get((x, y), 0)
|
||||
|
||||
def drag_axis_coordinate(self, x: int, y: int) -> int:
|
||||
return y if self.is_vertical else x
|
||||
|
||||
|
||||
@@ -927,6 +927,17 @@ class Tab: # {{{
|
||||
restored_scrollback: bytes = b'',
|
||||
) -> 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."
|
||||
# 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(
|
||||
use_shell=use_shell,
|
||||
cmd=cmd,
|
||||
@@ -2093,9 +2104,19 @@ class TabManager: # {{{
|
||||
self.recent_tab_bar_mouse_events.clear()
|
||||
return
|
||||
if button == GLFW_MOUSE_BUTTON_LEFT:
|
||||
close_tab_id = self.tab_bar.close_tab_id_at(int(x), int(y))
|
||||
if action == GLFW_PRESS:
|
||||
if close_tab_id:
|
||||
return # clicking the close button must not start a drag
|
||||
set_tab_being_dragged(tab.id, False, x, y)
|
||||
return
|
||||
if close_tab_id:
|
||||
if self.recent_tab_bar_mouse_events.click_count(GLFW_MOUSE_BUTTON_LEFT) == 1:
|
||||
set_tab_being_dragged()
|
||||
self.recent_tab_bar_mouse_events.clear()
|
||||
if (tab_to_close := self.tab_for_id(close_tab_id)) is not None:
|
||||
get_boss().close_tab(tab_to_close)
|
||||
return
|
||||
match self.recent_tab_bar_mouse_events.click_count(GLFW_MOUSE_BUTTON_LEFT):
|
||||
case 2:
|
||||
self.set_active_tab(tab)
|
||||
|
||||
+173
-2
@@ -148,6 +148,7 @@ if TYPE_CHECKING:
|
||||
from .fast_data_types import MousePosition
|
||||
from .file_transmission import FileTransmission
|
||||
from .notifications import OnlyWhen
|
||||
from .scrollback_search import ScrollbackSearch
|
||||
|
||||
|
||||
class CwdRequestType(Enum):
|
||||
@@ -283,6 +284,19 @@ def decode_cmdline(x: str) -> str:
|
||||
return ''
|
||||
|
||||
|
||||
def format_cmd_duration(seconds: float) -> str:
|
||||
"""Human readable duration for the notification sent when a command ends."""
|
||||
if seconds < 1:
|
||||
return f'{seconds * 1000:.0f}ms'
|
||||
if seconds < 60:
|
||||
return f'{seconds:.1f}s'
|
||||
minutes, secs = divmod(int(seconds), 60)
|
||||
if minutes < 60:
|
||||
return f'{minutes}m {secs}s'
|
||||
hours, minutes = divmod(minutes, 60)
|
||||
return f'{hours}h {minutes}m'
|
||||
|
||||
|
||||
class WindowDict(TypedDict):
|
||||
id: int
|
||||
is_focused: bool
|
||||
@@ -812,6 +826,12 @@ class Window:
|
||||
self.actions_on_focus_change: list[Callable[['Window', bool], None]] = []
|
||||
self.actions_on_removal: list[Callable[['Window'], 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.child_is_launched = False
|
||||
self.restored_scrollback = b''
|
||||
@@ -2056,6 +2076,8 @@ class Window:
|
||||
self.last_cmd_exit_status = int(exit_status)
|
||||
except Exception:
|
||||
self.last_cmd_exit_status = 0
|
||||
if (tab := self.tabref()) is not None:
|
||||
tab.mark_tab_bar_dirty()
|
||||
end_time = monotonic()
|
||||
last_cmd_output_duration = end_time - self.last_cmd_output_start_time
|
||||
self.last_cmd_output_start_time = 0.0
|
||||
@@ -2074,7 +2096,7 @@ class Window:
|
||||
cmd = nm.create_notification_cmd()
|
||||
cmd.title = 'kitty'
|
||||
s = self.last_cmd_cmdline.replace('\\\n', ' ')
|
||||
cmd.body = f'Command {s} finished with status: {exit_status}.\nClick to focus.'
|
||||
cmd.body = f'Command {s} finished in {format_cmd_duration(last_cmd_output_duration)} with status: {self.last_cmd_exit_status}.\nClick to focus.'
|
||||
cmd.only_when = OnlyWhen(when)
|
||||
if not nm.is_notification_allowed(cmd, self.id):
|
||||
return
|
||||
@@ -2096,7 +2118,7 @@ class Window:
|
||||
notify(self, opts, nm)
|
||||
self.screen.bell()
|
||||
elif action == 'command':
|
||||
open_cmd([x.replace('%c', self.last_cmd_cmdline).replace('%s', exit_status) for x in notify_cmdline])
|
||||
open_cmd([x.replace('%c', self.last_cmd_cmdline).replace('%s', str(self.last_cmd_exit_status)) for x in notify_cmdline])
|
||||
else:
|
||||
raise ValueError(f'Unknown action in option `notify_on_cmd_finish`: {action}')
|
||||
|
||||
@@ -2651,6 +2673,155 @@ class Window:
|
||||
w.screen.paste_bytes(sanitized)
|
||||
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:
|
||||
text = self.cmd_output(which, as_ansi=as_ansi, add_wrap_markers=add_wrap_markers)
|
||||
text = text.replace('\r\n', '\n').replace('\r', '\n')
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
#!/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'))
|
||||
@@ -279,3 +279,52 @@ class TestCommandPalette(BaseTest):
|
||||
def test_unmapped_actions_sorted_order(self):
|
||||
# Covered by test_collect_keys_bindings_sorted
|
||||
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'])
|
||||
@@ -0,0 +1,98 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPL v3 Copyright: 2026, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
import os
|
||||
import shutil
|
||||
import tempfile
|
||||
from unittest.mock import patch
|
||||
|
||||
from kitty.config import load_config
|
||||
from kitty.utils import log_error
|
||||
|
||||
from .base import BaseTest
|
||||
|
||||
|
||||
class TestConfigProfiles(BaseTest):
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
self.error_messages: list[str] = []
|
||||
log_error.redirect = self.error_messages.append
|
||||
self.tdir = tempfile.mkdtemp()
|
||||
self.conf = os.path.join(self.tdir, 'kitty.conf')
|
||||
|
||||
def tearDown(self):
|
||||
del log_error.redirect
|
||||
shutil.rmtree(self.tdir)
|
||||
super().tearDown()
|
||||
|
||||
def write_conf(self, text: str) -> str:
|
||||
with open(self.conf, 'w', encoding='utf-8') as f:
|
||||
f.write(text)
|
||||
return self.conf
|
||||
|
||||
def test_profile_overrides_only_the_options_it_declares(self):
|
||||
self.write_conf('font_size 13\n\nprofile work {\n font_size 9\n cursor_shape beam\n}\n')
|
||||
base = load_config(self.conf)
|
||||
self.ae(base.font_size, 13)
|
||||
self.ae(base.profile_name, '')
|
||||
work = load_config(self.conf, profile='work')
|
||||
self.ae(work.profile_name, 'work')
|
||||
self.ae(work.font_size, 9)
|
||||
self.assertNotEqual(work.cursor_shape, base.cursor_shape)
|
||||
# Options absent from the profile keep the global value
|
||||
self.ae(work.background_opacity, base.background_opacity)
|
||||
|
||||
def test_profile_is_selected_by_environment_variable(self):
|
||||
self.write_conf('font_size 13\nprofile dark {\n font_size 21\n}\n')
|
||||
with patch.dict(os.environ, {'KITTY_PROFILE': 'dark'}):
|
||||
self.ae(load_config(self.conf).font_size, 21)
|
||||
# An explicitly requested profile wins over the environment
|
||||
with patch.dict(os.environ, {'KITTY_PROFILE': 'dark'}):
|
||||
self.ae(load_config(self.conf, profile='').font_size, 21)
|
||||
self.write_conf('font_size 13\nprofile dark {\n font_size 21\n}\nprofile light {\n font_size 17\n}\n')
|
||||
self.ae(load_config(self.conf, profile='light').font_size, 17)
|
||||
|
||||
def test_unknown_profile_is_reported_without_blocking_startup(self):
|
||||
self.write_conf('font_size 13\n')
|
||||
opts = load_config(self.conf, profile='missing')
|
||||
self.ae(opts.font_size, 13)
|
||||
self.ae(opts.profile_name, 'missing')
|
||||
self.assertTrue(any('missing' in msg for msg in self.error_messages), self.error_messages)
|
||||
|
||||
def test_invalid_line_in_profile_does_not_block_startup(self):
|
||||
self.write_conf('font_size 12\nprofile work {\n font_size not-a-number\n background_opacity 0.5\n}\n')
|
||||
bad_lines = []
|
||||
opts = load_config(self.conf, profile='work', accumulate_bad_lines=bad_lines)
|
||||
self.ae(opts.font_size, 12)
|
||||
self.ae(opts.background_opacity, 0.5)
|
||||
self.ae(len(bad_lines), 1)
|
||||
self.assertIn('font_size not-a-number', bad_lines[0].line)
|
||||
self.ae(bad_lines[0].file, self.conf)
|
||||
|
||||
def test_unterminated_profile_is_reported(self):
|
||||
self.write_conf('profile work {\n font_size 9\n')
|
||||
bad_lines = []
|
||||
opts = load_config(self.conf, accumulate_bad_lines=bad_lines)
|
||||
self.ae(len(bad_lines), 1)
|
||||
self.assertIn('never closed', str(bad_lines[0].exception))
|
||||
self.assertNotEqual(opts.font_size, 9)
|
||||
|
||||
def test_profile_in_included_file(self):
|
||||
with open(os.path.join(self.tdir, 'extra.conf'), 'w', encoding='utf-8') as f:
|
||||
f.write('profile extra {\n font_size 30\n}\n')
|
||||
self.write_conf('include extra.conf\nfont_size 13\n')
|
||||
self.ae(load_config(self.conf, profile='extra').font_size, 30)
|
||||
self.ae(load_config(self.conf).font_size, 13)
|
||||
|
||||
def test_mappings_from_profile_are_added(self):
|
||||
self.write_conf('map ctrl+a new_tab\n\nprofile work {\n map ctrl+b new_window\n}\n')
|
||||
base = load_config(self.conf)
|
||||
work = load_config(self.conf, profile='work')
|
||||
self.ae(len(work.keyboard_modes[''].keymap), len(base.keyboard_modes[''].keymap) + 1)
|
||||
|
||||
def test_profile_name_on_command_line(self):
|
||||
from kitty.cli import parse_args
|
||||
|
||||
args, rest = parse_args(['--profile', 'work'])
|
||||
self.ae(args.profile, 'work')
|
||||
self.ae(rest, [])
|
||||
@@ -126,6 +126,16 @@ class TestDocks(BaseTest):
|
||||
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])
|
||||
|
||||
# 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):
|
||||
q = make_layout(Tall)
|
||||
windows = make_windows(q, 2)
|
||||
@@ -183,6 +193,9 @@ class TestDocks(BaseTest):
|
||||
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(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)
|
||||
# The decorations chosen by the layout for the owner are preserved
|
||||
self.ae(main.geometry.spaces.left - main.geometry.compensatory.left, DECORATION)
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
#!/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()
|
||||
@@ -834,3 +834,31 @@ class TestMouse(BaseTest):
|
||||
ac([], 4)
|
||||
self.assertTrue(s.callbacks.wtcbuf, 'the wheel event was not reported to the program')
|
||||
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)
|
||||
@@ -364,6 +364,18 @@ class TestNotifications(BaseTest):
|
||||
with tempfile.TemporaryDirectory() as tdir:
|
||||
do_test(self, tdir)
|
||||
|
||||
def test_command_finish_duration_formatting(self):
|
||||
from kitty.window import format_cmd_duration
|
||||
|
||||
self.ae(format_cmd_duration(0), '0ms')
|
||||
self.ae(format_cmd_duration(0.42), '420ms')
|
||||
self.ae(format_cmd_duration(1.0), '1.0s')
|
||||
self.ae(format_cmd_duration(59.94), '59.9s')
|
||||
self.ae(format_cmd_duration(60), '1m 0s')
|
||||
self.ae(format_cmd_duration(3599), '59m 59s')
|
||||
self.ae(format_cmd_duration(3600), '1h 0m')
|
||||
self.ae(format_cmd_duration(7325), '2h 2m')
|
||||
|
||||
def test_freedesktop_close_before_created(self):
|
||||
import kitty.fast_data_types as fdt
|
||||
|
||||
|
||||
@@ -29,6 +29,31 @@ class TestConfParsing(BaseTest):
|
||||
def test_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):
|
||||
launcher(self)
|
||||
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
#!/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')
|
||||
@@ -0,0 +1,145 @@
|
||||
#!/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
|
||||
+90
-9
@@ -1,11 +1,27 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPL v3 Copyright: 2026, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
import os
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
from kitty.fast_data_types import LEFT_EDGE, Color, Region, Screen
|
||||
from kitty.options.utils import tab_title_wrap
|
||||
from kitty.tab_bar import CellRange, DrawData, ExtraData, TabBar, TabBarData, TabExtent, WindowDropTarget, as_rgb, powerline_symbols, truncate_line, wrap_title
|
||||
from kitty.tab_bar import (
|
||||
CellRange,
|
||||
DrawData,
|
||||
ExtraData,
|
||||
TabBar,
|
||||
TabBarData,
|
||||
TabExtent,
|
||||
WindowDropTarget,
|
||||
abbreviate_path,
|
||||
as_rgb,
|
||||
exit_status_indicator,
|
||||
powerline_symbols,
|
||||
truncate_line,
|
||||
wrap_title,
|
||||
)
|
||||
from kitty.utils import color_as_int
|
||||
|
||||
from .base import BaseTest
|
||||
@@ -392,6 +408,47 @@ class TestTabBar(BaseTest):
|
||||
# empty line still gets ellipsis
|
||||
self.ae(truncate_line('', 4), '…')
|
||||
|
||||
def test_abbreviate_path(self) -> None:
|
||||
self.ae(abbreviate_path(''), '')
|
||||
self.ae(abbreviate_path('/home/user/projects/fws-kitty', '/home/user'), '~/p/fws-kitty')
|
||||
# the home directory itself has no component to abbreviate
|
||||
self.ae(abbreviate_path('/home/user', '/home/user'), '~')
|
||||
self.ae(abbreviate_path('/home/user/', '/home/user'), '~')
|
||||
# a trailing slash does not add an empty component
|
||||
self.ae(abbreviate_path('/usr/local/bin/'), '/u/l/bin')
|
||||
self.ae(abbreviate_path('/'), '/')
|
||||
self.ae(abbreviate_path('some/relative/dir'), 's/r/dir')
|
||||
# the last component is never abbreviated, it is the most informative
|
||||
self.ae(abbreviate_path('/home/user/a/very-long-project', '/home/user'), '~/a/very-long-project')
|
||||
# when the result is too wide, middle directories are elided rather
|
||||
# than cutting off the end of the title
|
||||
self.ae(abbreviate_path('/home/user/one/two/three/project', '/home/user', 14), '~/…/project')
|
||||
# when even that is too wide, the last component is truncated too
|
||||
self.ae(abbreviate_path('/home/user/a/very-long-final-dir', '/home/user', 12), '~/…/very-lo…')
|
||||
# widths are measured in terminal cells, so wide characters count double
|
||||
self.ae(abbreviate_path('/日本語/東京'), '/日/東京')
|
||||
|
||||
def test_exit_status_indicator(self) -> None:
|
||||
self.ae(exit_status_indicator(0), '')
|
||||
self.ae(exit_status_indicator(1), '✘ 1 ')
|
||||
self.ae(exit_status_indicator(130), '✘ 130 ')
|
||||
|
||||
def test_tab_title_indicators(self) -> None:
|
||||
home = os.path.expanduser('~')
|
||||
fake_tab = SimpleNamespace(
|
||||
active_window=SimpleNamespace(last_cmd_exit_status=127),
|
||||
get_cwd_of_active_window=lambda oldest=False: os.path.join(home, 'projects', 'fws-kitty'),
|
||||
)
|
||||
boss = SimpleNamespace(tab_for_id=lambda tab_id: fake_tab, mappings=SimpleNamespace(current_keyboard_mode_name=''))
|
||||
line = self.horizontal_tab_bar_line(
|
||||
['ignored'],
|
||||
60,
|
||||
boss=boss,
|
||||
tab_bar_style='separator',
|
||||
tab_title_template='{last_exit_code}:{exit_status_symbol}{tab.active_wd_abbreviated}',
|
||||
)
|
||||
self.assertIn('127:✘ 127 ~/p/fws-kitty', line)
|
||||
|
||||
def test_tab_title_wrap_option(self) -> None:
|
||||
for off in ('no', 'No', 'n', 'false', 'none', '0'):
|
||||
self.ae(tab_title_wrap(off), 0)
|
||||
@@ -601,7 +658,7 @@ class TestTabBar(BaseTest):
|
||||
[f' t0 {separator}', f'abcdefghijk{separator}', f'x {separator}'],
|
||||
)
|
||||
|
||||
def horizontal_tab_bar_line(self, titles: list[str], columns: int, **opts: object) -> str:
|
||||
def horizontal_tab_bar(self, titles: list[str], columns: int, boss: object | None = None, **opts: object) -> TabBar:
|
||||
self.set_options({'tab_title_template': '{title}', **opts})
|
||||
central = region(0, 0, columns * 10, 180)
|
||||
tab_bar = region(0, 180, columns * 10, 200)
|
||||
@@ -610,24 +667,48 @@ class TestTabBar(BaseTest):
|
||||
patch('kitty.tab_bar.viewport_for_window', return_value=(central, tab_bar, columns * 10, 200, 10, 20)),
|
||||
patch('kitty.tab_bar.set_tab_bar_render_data'),
|
||||
patch('kitty.tab_bar.update_tab_bar_edge_colors', return_value=None),
|
||||
patch('kitty.tab_bar.get_boss', return_value=DummyBoss()),
|
||||
patch('kitty.tab_bar.get_boss', return_value=boss if boss is not None else DummyBoss()),
|
||||
):
|
||||
tb = TabBar(1)
|
||||
tb.layout()
|
||||
tb.update(tuple(TabBarData(title=t, tab_id=i + 1, is_active=i == 0) for i, t in enumerate(titles)))
|
||||
return str(tb.screen.line(0)).rstrip()
|
||||
return tb
|
||||
|
||||
def horizontal_tab_bar_line(self, titles: list[str], columns: int, boss: object | None = None, **opts: object) -> str:
|
||||
return str(self.horizontal_tab_bar(titles, columns, boss, **opts).screen.line(0)).rstrip()
|
||||
|
||||
def test_horizontal_tab_bar_close_buttons(self) -> None:
|
||||
tb = self.horizontal_tab_bar(['one', 'two'], 40, tab_bar_style='separator')
|
||||
line = str(tb.screen.line(0))
|
||||
self.ae(line.count('×'), 2)
|
||||
# each close button is two cells wide, at the start of its tab
|
||||
self.ae(set(tb.close_button_cells.values()), {1, 2})
|
||||
for (cell_x, row), tab_id in tb.close_button_cells.items():
|
||||
px = tb.window_geometry.left + cell_x * tb.cell_width + 1
|
||||
py = tb.window_geometry.top + row * tb.cell_height + 1
|
||||
self.ae(tb.close_tab_id_at(px, py), tab_id)
|
||||
# clicking the title itself does not close the tab
|
||||
for te in tb.tab_extents:
|
||||
px = tb.window_geometry.left + te.x.end * tb.cell_width
|
||||
py = tb.window_geometry.top + 1
|
||||
self.ae(tb.close_tab_id_at(px, py), 0)
|
||||
self.ae(tb.close_tab_id_at(0, 0), 0)
|
||||
|
||||
# vertical tab bars keep closing with the middle mouse button
|
||||
self.ae(self.vertical_tab_bar().close_button_cells, {})
|
||||
|
||||
def test_horizontal_tab_bar_uses_free_space(self) -> None:
|
||||
line = self.horizontal_tab_bar_line
|
||||
# space not needed by short tabs goes to the long ones, instead of
|
||||
# being left unused at the end of the tab bar
|
||||
long_title = 'abcdefghijklmn'
|
||||
# two extra cells per tab are needed for its close button
|
||||
for style, columns, titles in (
|
||||
('fade', 25, ['1', long_title]),
|
||||
('fade', 35, ['1'] * 2 + [long_title]),
|
||||
('separator', 60, ['1'] * 8 + [long_title] * 2),
|
||||
('powerline', 80, ['1'] * 5 + [long_title] * 3),
|
||||
('slant', 126, ['1'] * 9 + [long_title] * 4),
|
||||
('fade', 29, ['1', long_title]),
|
||||
('fade', 41, ['1'] * 2 + [long_title]),
|
||||
('separator', 80, ['1'] * 8 + [long_title] * 2),
|
||||
('powerline', 96, ['1'] * 5 + [long_title] * 3),
|
||||
('slant', 152, ['1'] * 9 + [long_title] * 4),
|
||||
):
|
||||
text = line(titles, columns, tab_bar_style=style)
|
||||
self.ae(text.count(long_title), titles.count(long_title), (style, text))
|
||||
|
||||
@@ -0,0 +1,487 @@
|
||||
# Méthodologie de collaboration Git / GitHub
|
||||
|
||||
**Travail de binôme — document de référence**
|
||||
|
||||
| Élément | Valeur |
|
||||
| --- | --- |
|
||||
| Projet de référence | FWS-Kitty |
|
||||
| Binôme | *Damien Rochat* + *Gianmarco Ruberti* |
|
||||
| Date | Novembre 2026 |
|
||||
| Statut | Version 0.50.0 |
|
||||
|
||||
> Ce document décrit **comment nous travaillerions** sur ce projet dans un contexte professionnel. Aucune manipulation Git réelle n'est effectuée : les commandes et les exemples servent à illustrer concrètement la méthodologie.
|
||||
|
||||
---
|
||||
|
||||
## 1. Projet de référence
|
||||
|
||||
Le projet retenu comme contexte est **FWS-Kitty**, le fork FWS du terminal kitty, auquel notre équipe ajoute un panneau de gestion de fichiers (`kittens/file_manager/`) : navigation au clavier, création, renommage et suppression d'entrées, changement du répertoire courant du shell, ouverture de fichiers dans l'éditeur.
|
||||
|
||||
Ce projet est représentatif de notre futur quotidien professionnel :
|
||||
|
||||
- **Dépôt volumineux et historique existant** (C, Python, Go, docs Sphinx) : on ne réécrit pas l'existant, on s'y insère.
|
||||
- **Travail en parallèle** sur des zones différentes (interface Go du panneau, options Python, documentation, packaging Arch, CI).
|
||||
- **Un besoin de revue réel** : le code touche au shell de l'utilisateur (suppression de fichiers, `cd`), une erreur coûte cher.
|
||||
- **Des contrôles automatisables** : `./test.py`, `go test ./kittens/file_manager/`, `ruff check`, `./dev.sh build`, `./dev.sh docs`.
|
||||
|
||||
Le choix doit être **validé par l'enseignant avant de poursuivre** (voir tableau ci-dessus, ligne « Projet ETML d'origine »). Si un autre projet est validé, seuls les exemples de commandes changent : la méthodologie reste identique.
|
||||
|
||||
---
|
||||
|
||||
## 2. Organisation générale (question a)
|
||||
|
||||
### 2.1 Structure d'équipe et rôles
|
||||
|
||||
Nous sommes un binôme, donc chaque rôle est tenu par les deux personnes, mais avec une **responsabilité principale** clairement attribuée pour éviter les zones grises (le « responsable » décide, l'autre relit).
|
||||
|
||||
| Rôle | Responsabilités | Qui |
|
||||
| --- | --- | --- |
|
||||
| **Mainteneur / intégrateur** | Protège `main`, arbitre les désaccords techniques, valide les fusions, tient le `CHANGELOG` et les tags de version | *(binôme A)* |
|
||||
| **Développeur·se / relecteur·se** | Développe les fonctionnalités, relit toutes les PR, vérifie les critères de validation | *(binôme B)* |
|
||||
| **Responsable qualité** | Surveille la CI, le lint, les tests, signale les régressions | Alternance par itération |
|
||||
| **Responsable documentation** | Vérifie que chaque PR met à jour `README.md` / `docs/` | Alternance par itération |
|
||||
|
||||
Les deux membres sont **co-responsables de la relecture** : aucune PR n'est fusionnée sans avoir été lue par l'autre. Règle d'or : *celui qui écrit le code ne valide jamais seul sa propre PR*.
|
||||
|
||||
### 2.2 Répartition du travail
|
||||
|
||||
- Découpage **par fonctionnalité verticale** (de la logique Go jusqu'à la doc), pas par couche technique (sinon tout le monde touche les mêmes fichiers et les conflits explosent).
|
||||
- Une **issue = un périmètre = une branche = une PR**. Si une issue grossit, on la scinde.
|
||||
- Pour le projet de référence : une personne prend « création / renommage / suppression de fichiers », l'autre « changement de répertoire et intégration shell », puis on échange les rôles sur les itérations suivantes pour que chacun connaisse tout le code.
|
||||
|
||||
### 2.3 Communication
|
||||
|
||||
| Canal | Usage | Fréquence |
|
||||
| --- | --- | --- |
|
||||
| **GitHub Issues / PR** | Canal **officiel** : toute décision technique qui compte est écrite ici | Continu |
|
||||
| **GitHub Discussions** | Questions ouvertes, choix d'architecture, sondages | Au besoin |
|
||||
| **Discord (salon privé du binôme)** | Synchronisation rapide, blocages, partage d'écran | Quotidien |
|
||||
| **Visio / point de 15 min** | Point de départ et point de fin de journée : qui fait quoi, qu'est-ce qui bloque | 1 à 2 fois/jour |
|
||||
| **Revue de fin d'itération** | Bilan, reste à faire, mise à jour du Kanban | 1 fois/semaine |
|
||||
|
||||
**Règle de traçabilité de la communication** : une décision prise à l'oral ou sur Discord est **retranscrite dans l'issue ou la PR** concernée avant d'être appliquée. « Si ce n'est pas écrit sur GitHub, ça n'existe pas. » Cela évite les désaccords une semaine plus tard et documente le *pourquoi* des choix.
|
||||
|
||||
### 2.4 Outils complémentaires à GitHub
|
||||
|
||||
| Besoin | Outil retenu | Justification |
|
||||
| --- | --- | --- |
|
||||
| Suivi des tâches | **GitHub Projects** (board Kanban) | Intégré au dépôt : une issue = une carte, aucune double saisie, pas d'outil tiers à administrer |
|
||||
| Communication écrite | GitHub Issues + Discussions, complété par Discord | Le suivi reste sur GitHub, Discord ne sert qu'au temps réel |
|
||||
| Documentation technique | Markdown dans `docs/` (versionné) + `README.md` | La doc évolue dans la même PR que le code |
|
||||
| Intégration continue | **GitHub Actions** | Natif, gratuit sur dépôt public, pas de serveur à maintenir |
|
||||
| Qualité / formatage | `ruff`, `go vet`/`gofmt`, `./test.py`, hooks `pre-commit` | Déjà présents dans le dépôt |
|
||||
| Maquettes / captures | Fichiers versionnés dans `docs/` + commentaire de PR | On garde la trace de l'état avant/après |
|
||||
|
||||
*Alternatives écartées* : Jira et Trello ajoutent un outil et une saisie en double sans apporter de valeur à un binôme ; les tickets vivent déjà dans les issues GitHub, qui sont liées nativement aux commits et aux PR.
|
||||
|
||||
### 2.5 Transparence et suivi des tâches
|
||||
|
||||
1. **Toute demande commence par une issue** (bug, fonctionnalité, tâche technique) avec un gabarit : contexte, résultat attendu, critères d'acceptation, labels.
|
||||
2. **Un board Kanban unique** avec cinq colonnes : `Backlog` → `À faire` → `En cours` (max 1 carte par personne) → `En revue` → `Terminé`.
|
||||
3. **Une seule carte « En cours » par personne** : le travail en cours est visible d'un coup d'œil, on évite le multitâche.
|
||||
4. **Labels normalisés** : `type: feat|fix|docs|chore`, `prio: haute|moyenne|basse`, `zone: go|python|docs|packaging|ci`, `état: bloqué`.
|
||||
5. **Mise à jour en fin de journée** : la carte reflète l'état réel, avec un commentaire de statut si elle stagne.
|
||||
6. **Lien bidirectionnel systématique** : l'issue référence la PR (« Ferme #42 »), la PR référence l'issue, le commit référence l'issue.
|
||||
7. **Journal de décisions** : les choix structurants (workflow, format de fichier de config, découpage) sont consignés dans une issue étiquetée `décision` ou dans un court ADR (`docs/adr/NNN-titre.md`).
|
||||
|
||||
---
|
||||
|
||||
## 3. Workflow Git / GitHub (question b)
|
||||
|
||||
### 3.1 Workflow retenu : **GitHub Flow (trunk-based simplifié)**
|
||||
|
||||
Une seule branche longue (`main`, toujours déployable), des branches de travail **courtes** (1 à 3 jours), une Pull Request obligatoire pour intégrer.
|
||||
|
||||
| Critère | GitHub Flow (retenu) | Git Flow | Feature Branch « pur » |
|
||||
| --- | --- | --- | --- |
|
||||
| Complexité | Faible | Élevée (2 branches longues + 3 types) | Faible |
|
||||
| Adapté au binôme | Oui | Non : la `develop` devient un goulot d'étranglement | Oui |
|
||||
| Fréquence d'intégration | Élevée, conflits rares | Faible, gros merges | Moyenne |
|
||||
| Livraisons | Continu, tag sur `main` | Par release planifiée | Au cas par cas |
|
||||
| Historique | Linéaire et lisible | Encombré de merges | Linéaire |
|
||||
|
||||
**Justification du choix** : nous sommes deux, avec des itérations courtes et un besoin de retours rapides. Git Flow a été conçu pour des équipes nombreuses livrant des versions planifiées ; à deux, sa branche `develop` ajoute une étape de synchronisation sans bénéfice. Le Feature Branch « pur » n'impose pas de règle de fusion : il ne protège pas `main`. GitHub Flow combine les avantages : branches courtes (peu de conflits), `main` protégée (qualité), et intégration continue (feedback immédiat).
|
||||
|
||||
### 3.2 Organisation des branches
|
||||
|
||||
| Branche | Rôle | Durée de vie | Protection |
|
||||
| --- | --- | --- | --- |
|
||||
| `main` | Référence unique, **toujours compilable et testée** ; c'est elle qui est empaquetée | Permanente | Protégée : PR obligatoire, 1 approbation, CI verte, pas de push direct, pas de force-push |
|
||||
| `feat/<description>` | Nouvelle fonctionnalité | ≤ 3 jours | Aucune (mais CI obligatoire avant PR) |
|
||||
| `fix/<description>` | Correction de bug (issue existante) | ≤ 1 jour | Aucune |
|
||||
| `docs/<description>` | Documentation seule | ≤ 1 jour | Aucune |
|
||||
| `chore/<description>`, `ci/<description>`, `refactor/<description>` | Maintenance, CI, refonte sans changement de comportement | ≤ 2 jours | Aucune |
|
||||
| `hotfix/<description>` | Correction urgente d'une version livrée | Quelques heures | Part de `main`, fusionnée puis taguée `PATCH` |
|
||||
| `release/x.y.z` | **Uniquement si** une version doit être stabilisée avant livraison | Quelques jours | Créée depuis `main`, sert aux correctifs de dernière minute |
|
||||
|
||||
**Pas de branche `develop`** : `main` joue ce rôle, puisque chaque PR fusionnée est déjà revue et testée.
|
||||
|
||||
**Nommage** (`kebab-case`, en anglais, court et explicite — cohérent avec les conventions du dépôt) :
|
||||
|
||||
```
|
||||
feat/file-manager-panel
|
||||
feat/file-manager-create-entry
|
||||
fix/file-manager-cd-dock
|
||||
docs/file-manager-shortcuts
|
||||
chore/update-dependencies
|
||||
hotfix/version-string
|
||||
```
|
||||
|
||||
Interdits : `ma-branche`, `test`, `wip`, `buffy-2`, les prénoms, les dates, les majuscules et les accents. Une branche doit décrire **l'intention**, pas la personne.
|
||||
|
||||
**Suppression après fusion** : la branche est supprimée automatiquement (option GitHub « Automatically delete head branches ») pour garder un dépôt lisible.
|
||||
|
||||
### 3.3 Cycle complet d'une contribution
|
||||
|
||||
```sh
|
||||
# 1. Se synchroniser
|
||||
git switch main
|
||||
git pull --ff-only
|
||||
|
||||
# 2. Créer la branche de travail (nommée d'après l'issue #42)
|
||||
git switch -c feat/file-manager-create-entry
|
||||
|
||||
# 3. Travailler par petits commits
|
||||
git add kittens/file_manager/main.go
|
||||
git commit -m "feat(file-manager): add file creation from status line"
|
||||
|
||||
# 4. Se resynchroniser régulièrement sur main (évite les gros conflits)
|
||||
git fetch origin
|
||||
git rebase origin/main # branche personnelle uniquement
|
||||
|
||||
# 5. Pousser tôt, pousser souvent
|
||||
git push -u origin feat/file-manager-create-entry
|
||||
|
||||
# 6. Ouvrir une Pull Request (gabarit rempli, CI verte, relecteur assigné)
|
||||
gh pr create --fill --reviewer <binôme>
|
||||
|
||||
# 7. Corriger les retours, puis fusionner en "Squash and merge"
|
||||
git switch main && git pull --ff-only
|
||||
```
|
||||
|
||||
Règles de fusion :
|
||||
|
||||
- **Squash and merge** pour les branches de fonctionnalité : un commit propre par PR dans `main`, l'historique reste lisible et linéaire.
|
||||
- **Merge commit** réservé aux fusions `release/*` / `hotfix/*` pour conserver la trace des deux lignées.
|
||||
- **Rebase and merge** interdit sur `main` : il réécrit les commits déjà revus.
|
||||
|
||||
### 3.4 Protection de `main` (réglages GitHub)
|
||||
|
||||
1. Pull Request obligatoire avant fusion, **aucun push direct** (règle appliquée aussi aux mainteneurs).
|
||||
2. **1 approbation minimum** ; une nouvelle approbation est exigée après chaque push significatif (option « Dismiss stale approvals »).
|
||||
3. **Statuts de CI obligatoires** : `lint`, `tests`, `build`.
|
||||
4. Branche à jour avec `main` avant fusion ; **conversations résolues** obligatoires.
|
||||
5. Force-push et suppression de `main` interdits ; commits **signés** (bonne pratique déjà suivie dans l'organisation FWS).
|
||||
6. `CODEOWNERS` sur `kittens/file_manager/`, `packaging/` et `docs/` : la PR touche ces zones → le relecteur est désigné automatiquement.
|
||||
|
||||
### 3.5 Politique de versionnage : **SemVer 2.0.0**
|
||||
|
||||
Format `MAJEUR.MINEUR.CORRECTIF`, tags Git préfixés `v` :
|
||||
|
||||
| Incrément | Quand | Exemple |
|
||||
| --- | --- | --- |
|
||||
| `MAJEUR` | Changement incompatible (option renommée, comportement cassé, config illisible) | `v1.0.0` |
|
||||
| `MINEUR` | Nouvelle fonctionnalité rétrocompatible (nouvelle action `mkdir`, nouveau raccourci) | `v0.51.0` |
|
||||
| `CORRECTIF` | Correction rétrocompatible (bug, doc erronée d'une option) | `v0.51.1` |
|
||||
|
||||
- Avant la première version stable : `0.y.z`, tout peut bouger, mais on reste rigoureux sur `z`.
|
||||
- Pré-versions : `v0.51.0-rc.1` (release candidate), `v0.51.1-beta.2`.
|
||||
- **Tag annoté et signé** sur `main`, jamais sur une branche de travail :
|
||||
```sh
|
||||
git tag -s v0.51.0 -m "file-manager: create, rename, delete entries"
|
||||
git push origin v0.51.0
|
||||
```
|
||||
- **`CHANGELOG.md` mis à jour dans la PR de release** (sections `Ajouté`, `Modifié`, `Corrigé`, `Supprimé`, `Sécurité`), et **release GitHub** créée depuis le tag avec les notes correspondantes.
|
||||
- Une version livrée ne se modifie jamais : on publie un `CORRECTIF`, on ne réécrit pas un tag existant.
|
||||
|
||||
### 3.6 Convention de commits : **Conventional Commits 1.0.0**
|
||||
|
||||
Format : `<type>(<portée>): <description impérative>`, **en anglais**, titre ≤ 72 caractères, corps optionnel expliquant le *pourquoi*.
|
||||
|
||||
| Type | Usage |
|
||||
| --- | --- |
|
||||
| `feat` | Nouvelle fonctionnalité visible par l'utilisateur |
|
||||
| `fix` | Correction de bug |
|
||||
| `docs` | Documentation uniquement |
|
||||
| `style` | Formatage, espaces (aucun changement de comportement) |
|
||||
| `refactor` | Réécriture interne sans changement de comportement |
|
||||
| `perf` | Amélioration de performance |
|
||||
| `test` | Ajout ou correction de tests |
|
||||
| `build` | Système de build, dépendances, packaging |
|
||||
| `ci` | Configuration de l'intégration continue |
|
||||
| `chore` | Tâches annexes (`.gitignore`, scripts) |
|
||||
| `revert` | Annulation d'un commit précédent |
|
||||
|
||||
Exemples conformes :
|
||||
|
||||
```
|
||||
feat(file-manager): add directory creation with shift+n
|
||||
fix(file-manager): keep cd working when panel runs in a dock
|
||||
docs(file-manager): document default key bindings
|
||||
refactor(file-manager): extract path formatting into a helper
|
||||
test(file-manager): cover truncateToWidth with wide characters
|
||||
ci: run go tests for the file manager kitten
|
||||
```
|
||||
|
||||
Règles complémentaires :
|
||||
|
||||
- **Un commit = un changement cohérent** qui compile et dont les tests passent.
|
||||
- **Impératif présent** (« add », pas « added » ni « adds ») : le commit décrit ce qu'il fait.
|
||||
- **Pas de commits fourre-tout** (`wip`, `fix stuff`, `update`) : ils sont écrasés par le squash avant fusion, mais polluent la relecture.
|
||||
- **Référence à l'issue** dans le corps ou le pied : `Refs #42`, `Fixes #42`, `Closes #42` (fermeture automatique).
|
||||
- **Breaking change** : `feat(config)!: rename sort_by values` + pied `BREAKING CHANGE: …` → déclenche un `MAJEUR` (ou `0.y` incrémenté).
|
||||
- Gabarit local (`.gitmessage`) et hook `commit-msg` (Commitlint) pour vérifier le format avant même le push.
|
||||
|
||||
---
|
||||
|
||||
## 4. Processus de revue de code (question c)
|
||||
|
||||
### 4.1 Déroulement d'une Pull Request
|
||||
|
||||
1. **Ouverture précoce en brouillon** (`Draft PR`) dès le premier commit poussé : la CI tourne, l'autre peut suivre l'avancement. Aucune revue formelle demandée tant qu'elle est en brouillon.
|
||||
2. **PR prête** : description remplie grâce au gabarit (contexte, issue liée, ce qui a changé, comment tester, captures si l'affichage change), relecteur assigné, labels posés.
|
||||
3. **CI** : `lint` + `tests` + `build` doivent être verts. Une PR rouge n'est **pas relue en profondeur** : l'auteur corrige d'abord.
|
||||
4. **Revue** par l'autre membre, sous **24 h ouvrées** (objectif : quelques heures). Trois verdicts possibles : *Approve*, *Request changes* (bloquant, avec justification), *Comment* (non bloquant).
|
||||
5. **Corrections** par l'auteur, en commits supplémentaires (pas de force-push pendant la revue, pour que le relecteur voie le diff incrémental).
|
||||
6. **Approbation finale** puis **squash and merge**, suppression de la branche, carte Kanban déplacée en `Terminé`.
|
||||
7. **Post-merge** : vérification que `main` reste verte (CI sur `main`), et mise à jour de la doc/du `CHANGELOG` si nécessaire.
|
||||
|
||||
### 4.2 Nombre d'approbations
|
||||
|
||||
| Contexte | Approbations requises | Pourquoi |
|
||||
| --- | --- | --- |
|
||||
| Binôme (notre cas) | **1 approbation** par l'autre membre + CI verte | 2 approbations sont impossibles : l'auteur ne peut pas approuver sa propre PR, l'exiger bloquerait tout le monde |
|
||||
| Équipe de 3 à 5 | **2 approbations** | Réduit le risque d'angle mort et partage la connaissance |
|
||||
| Équipe > 5 / code critique | **2 approbations dont un `CODEOWNER`** | Le propriétaire de la zone est garant de sa cohérence |
|
||||
| `hotfix` en urgence | **1 approbation**, rétro-revue sous 48 h | On débloque la production sans perdre la trace |
|
||||
|
||||
**Notre règle** : 1 approbation humaine **plus** les contrôles automatiques obligatoires. Le relecteur ne « remplace » pas la CI et la CI ne remplace pas le relecteur : les deux sont nécessaires. Une PR approuvée dont un nouveau commit casse la CI repasse en revue (l'approbation est invalidée).
|
||||
|
||||
### 4.3 Critères de validation avant fusion (Definition of Done)
|
||||
|
||||
Une PR n'est fusionnable que si **tous** ces points sont vrais :
|
||||
|
||||
- [ ] L'issue est liée (`Fixes #…`) et les critères d'acceptation sont couverts.
|
||||
- [ ] **CI verte** : `lint` (`ruff check`, `gofmt`/`go vet`), `tests` (`go test ./kittens/file_manager/`, `./test.py` pertinents), `build` (`./dev.sh build`).
|
||||
- [ ] **Code relu et approuvé** par l'autre membre ; tous les commentaires sont résolus.
|
||||
- [ ] **Commits clairs** : format Conventional Commits, messages en anglais, pas de `wip` résiduel.
|
||||
- [ ] **Aucun fichier parasite** versionné : pas de `*_generated.go`, `dependencies/`, fichiers d'environnement, secrets, artefacts de build (voir `.gitignore`).
|
||||
- [ ] **Documentation à jour** : `README.md`, `docs/kittens/file-manager.rst`, aide des options si un réglage est ajouté ou renommé.
|
||||
- [ ] **Tests ajoutés** pour toute nouvelle logique (fonctions pures du panneau, cas limites : caractères larges, chemins vides, permissions).
|
||||
- [ ] **Pas de régression** : les cas d'erreur restent gérés (répertoire non vide, fichier non inscriptible).
|
||||
- [ ] **Portée respectée** : la PR ne fait que ce que dit l'issue ; le reste part dans une autre PR.
|
||||
- [ ] **Branche à jour** avec `main` et **pas de conflit**.
|
||||
- [ ] **Performance** : pas de boucle coûteuse ajoutée dans le rendu (un benchmark est joint si la PR touche le chemin chaud).
|
||||
- [ ] **Sécurité** : aucune commande shell construite par concaténation non échappée, aucun secret dans le diff.
|
||||
|
||||
Gabarit de PR (`.github/pull_request_template.md`, résumé) :
|
||||
|
||||
```md
|
||||
## Contexte
|
||||
Fixes #42 — création de fichiers depuis la ligne d'état.
|
||||
|
||||
## Changements
|
||||
- `main.go` : action `create_file`.
|
||||
- `main.py` : raccourci `n` et option `show_hidden` vérifiée.
|
||||
|
||||
## Comment tester
|
||||
1. `./dev.sh build`
|
||||
2. `kitten file-manager ~/tmp`, puis `n`, saisir `test.txt`
|
||||
|
||||
## Checklist
|
||||
- [ ] CI verte - [ ] Tests ajoutés - [ ] Doc mise à jour - [ ] Aucun secret
|
||||
```
|
||||
|
||||
### 4.4 Bonnes pratiques de revue
|
||||
|
||||
- **PR courtes** : viser **≤ 400 lignes modifiées**. Au-delà, le taux de détection de bugs s'effondre ; on découpe.
|
||||
- **Relire le code, pas la personne** : commenter le comportement et proposer une alternative, jamais juger l'auteur.
|
||||
- **Commentaires actionnables** : « Ici, `filepath.Join` évite le cas `//` sur Windows » plutôt que « c'est mauvais ».
|
||||
- **Préfixer le niveau d'exigence** : `[bloquant]`, `[suggestion]`, `[question]`, `[nit]` pour distinguer ce qui empêche la fusion du simple confort.
|
||||
- **Ne pas réécrire la PR de l'autre** : on propose, l'auteur applique (sauf correction triviale de coquille, annoncée en commentaire).
|
||||
- **Le relecteur vérifie en local** quand le changement est subtil (`git fetch origin && git switch <branche>`, puis test manuel) : le diff ne remplace pas l'exécution.
|
||||
- **Pas de « LGTM » sec** : une approbation indique ce qui a été vérifié (code lu, tests lancés, cas limites testés).
|
||||
|
||||
---
|
||||
|
||||
## 5. Bonnes pratiques de collaboration (question d)
|
||||
|
||||
### 5.1 Fréquence de commit et de push
|
||||
|
||||
| Action | Fréquence recommandée | Raison |
|
||||
| --- | --- | --- |
|
||||
| **Commit** | À chaque unité de travail cohérente : 3 à 10 par jour, ~50 à 200 lignes | Point de sauvegarde, message lisible, retour arrière ciblé |
|
||||
| **Push** | **Au moins 1 fois par demi-journée**, et toujours en fin de journée | Sauvegarde distante, CI lancée tôt, travail visible du binôme |
|
||||
| **Pull request** | Dès que la fonctionnalité est testable (même incomplète, en brouillon) | Relecture précoce, conflits détectés tôt |
|
||||
| **Synchronisation `main`** | Chaque matin + dès qu'une PR est fusionnée | Branche courte = conflits rares et simples |
|
||||
|
||||
Anti-modèles : garder 3 jours de travail non poussé (perte de données, conflit géant), pousser 20 fois par heure des commits `wip` non relisibles, ouvrir une PR de 2 000 lignes.
|
||||
|
||||
### 5.2 Gestion des conflits de merge
|
||||
|
||||
**Prévention (le plus important)** :
|
||||
|
||||
1. Branches **courtes** et périmètre étroit ; découpage par fichier/zone pour que les deux ne touchent pas les mêmes lignes.
|
||||
2. `git fetch` + `rebase origin/main` **quotidien** sur sa branche personnelle.
|
||||
3. Fichiers sensibles aux conflits (`CHANGELOG.md`, fichiers générés) : on ne les édite pas dans deux branches en parallèle ; le `CHANGELOG` est consolidé dans la PR de release.
|
||||
4. Formateurs et fins de ligne imposés (`.editorconfig`, `.gitattributes`) : pas de faux conflits de whitespace/CRLF.
|
||||
|
||||
**Résolution** :
|
||||
|
||||
```sh
|
||||
git fetch origin
|
||||
git switch feat/file-manager-create-entry
|
||||
git rebase origin/main
|
||||
# conflit : git status liste les fichiers
|
||||
# résoudre à la main, puis :
|
||||
git add <fichier-résolu>
|
||||
git rebase --continue
|
||||
# en cas de doute, repartir de zéro :
|
||||
git rebase --abort
|
||||
```
|
||||
|
||||
- **On ne résout jamais un conflit sans comprendre les deux versions** : `git log --merge -p <fichier>` et l'issue/PR d'origine donnent l'intention de chaque côté.
|
||||
- **Résolution testée** : après un rebase, `./dev.sh build` + tests concernés, puis `git push --force-with-lease` (jamais `--force` nu).
|
||||
- **Escalade** : si le conflit dépasse 15 minutes ou touche du code que l'autre connaît mieux, **on s'appelle**. On ne fusionne pas un conflit à l'aveugle pour « avancer ».
|
||||
- **Sur une branche partagée**, jamais de rebase : on fusionne `main` dans la branche (`git merge origin/main`), sinon tous les relecteurs perdent la trace.
|
||||
- Conflits récurrents = signal d'alerte : on revoit le découpage des tâches, pas seulement le conflit.
|
||||
|
||||
### 5.3 Traçabilité des décisions
|
||||
|
||||
Chaque décision doit pouvoir être retrouvée en remontant la chaîne **issue → branche → commit → PR → tag** :
|
||||
|
||||
- **Issue** : le *quoi* et le *pourquoi* (contexte, critères d'acceptation). Numérotée, étiquetée, assignée.
|
||||
- **Branche** : porte le numéro de l'issue quand c'est naturel (`feat/42-create-entry`).
|
||||
- **Commit** : Conventional Commits, corps expliquant le *pourquoi* d'un choix non évident (compromis, cas limite).
|
||||
- **PR** : description complète, discussion de revue, décisions actées. Une PR référence l'issue (`Fixes #42`), l'issue référence la PR.
|
||||
- **ADRs** : décision structurante → court fichier `docs/adr/003-squash-and-merge.md` (contexte, options, décision, conséquences), commité. Immutable : une nouvelle décision remplace l'ancienne par un nouvel ADR.
|
||||
- **`CHANGELOG.md`** : ce qui change pour l'utilisateur, par version.
|
||||
- **Labels + board** : état du travail visible sans lire tout l'historique.
|
||||
- **Messages de PR/commit sans mention d'outil** : on documente le changement et sa raison, jamais l'assistant ou l'outil utilisé.
|
||||
|
||||
### 5.4 Garantir la qualité avant intégration
|
||||
|
||||
| Niveau | Contrôle | Quand |
|
||||
| --- | --- | --- |
|
||||
| **Local** | hooks `pre-commit` (ruff, gofmt, détection de secrets), `.gitmessage` | Avant chaque commit |
|
||||
| **Branche** | CI GitHub Actions : lint, tests unitaires, build | À chaque push |
|
||||
| **PR** | Mémoire : gabarit rempli, checklist cochée, CI obligatoire | Avant revue |
|
||||
| **Revue** | Relecture humaine, test local si nécessaire, 1 approbation | Avant fusion |
|
||||
| **`main`** | CI sur `main` après fusion, tag SemVer, release notes | À chaque fusion importante |
|
||||
|
||||
Pipeline CI cible (`.github/workflows/ci.yml`, extrait) :
|
||||
|
||||
```yaml
|
||||
name: CI
|
||||
on:
|
||||
pull_request:
|
||||
push:
|
||||
branches: [main]
|
||||
jobs:
|
||||
lint:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- run: ruff check .
|
||||
- run: gofmt -l . && go vet ./kittens/file_manager/
|
||||
tests:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- run: go test ./kittens/file_manager/
|
||||
- run: ./test.py type-check
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- run: ./dev.sh deps && ./dev.sh build
|
||||
```
|
||||
|
||||
- **`main` reste toujours verte** : c'est la garantie qu'un `pull` ne casse pas le travail de l'autre.
|
||||
- **Règles d'hygiène** : `.gitignore` à la racine, jamais de secrets/`.env`, jamais de `git add .` aveugle, jamais de `git push --force` sur une branche partagée, commits signés.
|
||||
- **Dette technique** : chaque `TODO` ou contournement crée une issue étiquetée `dette` ; on ne le laisse pas dans un commentaire orphelin.
|
||||
|
||||
### 5.5 Rythme de travail et discipline d'équipe
|
||||
|
||||
- **Point quotidien de 15 min** : hier / aujourd'hui / bloqué.
|
||||
- **Revue croisée systématique** : personne ne fusionne sans l'autre.
|
||||
- **Arrêt propre** : en fin de journée, la branche est poussée, la carte Kanban est à jour, l'état est décrit en commentaire si le travail est incomplet.
|
||||
- **Pas de travail « fantôme »** : un gros chantier en local pendant une semaine est interdit ; on découpe, on pousse, on montre.
|
||||
- **Bilan d'itération** : ce qui a marché, ce qui a coincé, un ajustement de la méthodologie (ce document est versionné et évolue).
|
||||
|
||||
---
|
||||
|
||||
## 6. Justification du choix : avantages et limites
|
||||
|
||||
### Avantages
|
||||
|
||||
1. **Feedback rapide** : branches de 1 à 3 jours + CI sur chaque push → une erreur est détectée en heures, pas en fin de projet.
|
||||
2. **`main` fiable** : chaque commit de `main` est revu, linté, testé, compilé. On peut livrer ou repartir d'une base saine à tout moment.
|
||||
3. **Conflits limités** : branches courtes, rebase quotidien, découpage par zone ; les rares conflits restent petits et compréhensibles.
|
||||
4. **Traçabilité complète** : issue → branche → commit → PR → tag ; on peut justifier chaque ligne et chaque décision des mois plus tard.
|
||||
5. **Qualité partagée** : la relecture croisée diffuse la connaissance des deux zones du code et évite le bus factor de 1.
|
||||
6. **Coût d'outillage quasi nul** : tout vit dans GitHub (issues, board, PR, CI, releases), rien à installer ni à administrer.
|
||||
7. **Historique lisible** : squash + Conventional Commits + tags SemVer donnent un journal clair, exploitable pour un `CHANGELOG` et des releases automatiques.
|
||||
8. **Transposable** : ces règles s'appliquent telles quelles à une équipe de 5 ou 10 (2 approbations, CODEOWNERS), ce qui correspond à un contexte professionnel.
|
||||
|
||||
### Limites et parades
|
||||
|
||||
| Limite | Parade retenue |
|
||||
| --- | --- |
|
||||
| **Une seule approbation** = un seul regard, angle mort possible | Checklist obligatoire, CI stricte, relecture en local pour les changements subtils, 2 approbations dès qu'une 3ᵉ personne rejoint |
|
||||
| **Pas de branche `develop`** : pas de zone de stabilisation longue | Branches `release/*` créées ponctuellement quand une version doit être gelée |
|
||||
| **Coût de la revue** : avec deux personnes, l'attente de relecture peut bloquer | Objectif de réponse < 24 h, PR courtes, revue en priorité sur le développement ; `Draft PR` pour partager tôt |
|
||||
| **Discipline nécessaire** : GitHub Flow s'effondre si les branches durent des semaines | Règle des 3 jours, découpage des issues, point quotidien, indicateur « âge des branches ouvertes » |
|
||||
| **Squash** : perte de la granularité des commits intermédiaires | Commits soignés quand même (utiles à la revue), et merge commit pour les `release/*` / `hotfix/*` |
|
||||
| **Petit effectif** : rôles cumulés, risque de relâchement sur la doc et la CI | Rôles tournants par itération, checklist non négociable, CI bloquante sur `main` |
|
||||
| **Conventions à apprendre** (Conventional Commits, SemVer) | `.gitmessage` + Commitlint en local, exemples dans ce document, rappel dans `CONTRIBUTING.md` |
|
||||
| **Dépendance à GitHub** | Le dépôt Git reste la source de vérité (utilisable hors ligne) ; le workflow ne repose pas sur une fonctionnalité propriétaire indispensable |
|
||||
|
||||
### Alternatives écartées, en résumé
|
||||
|
||||
- **Git Flow** : surdimensionné pour deux développeurs ; `develop` + `release` + `hotfix` permanents créent de l'attente et des merges massifs.
|
||||
- **Feature Branch sans PR** : rien ne garantit la qualité de `main`, et la revue devient optionnelle.
|
||||
- **Trunk-based avec développement direct sur `main`** : trop risqué ici — le code touche au shell (suppression de fichiers, `cd`), une régression non revue est coûteuse ; viable avec des feature flags et une CI très mature, ce qui n'est pas l'objectif du projet.
|
||||
|
||||
---
|
||||
|
||||
## 7. Récapitulatif — la méthodologie en dix lignes
|
||||
|
||||
1. Une **seule branche longue** : `main`, protégée, toujours verte.
|
||||
2. Des branches de travail **courtes** nommées `type/description` (≤ 3 jours).
|
||||
3. **Une issue = une branche = une PR**, périmètre strict.
|
||||
4. Workflow **GitHub Flow**, fusion en **squash and merge**.
|
||||
5. **Conventional Commits** en anglais, un commit = un changement cohérent.
|
||||
6. **SemVer** + tags signés `vX.Y.Z` + `CHANGELOG`.
|
||||
7. **PR obligatoire** : gabarit rempli, CI verte, checklist cochée.
|
||||
8. **1 approbation** par le binôme (2 dès une équipe de 3+).
|
||||
9. **Push au moins deux fois par jour**, rebase quotidien, conflits résolus à deux.
|
||||
10. **Toute décision est écrite sur GitHub** : issue, PR ou ADR — sinon elle n'existe pas.
|
||||
|
||||
---
|
||||
|
||||
## 8. Annexes
|
||||
|
||||
### 8.1 Checklist express avant de demander une revue
|
||||
|
||||
```
|
||||
[ ] Ma branche est à jour avec main et la CI est verte
|
||||
[ ] Mon diff fait moins de ~400 lignes, sinon il est découpé
|
||||
[ ] J'ai lié l'issue et rempli la description (contexte, tests)
|
||||
[ ] J'ai relu mon propre diff (git diff main...HEAD)
|
||||
[ ] Aucun fichier généré, secret ou artefact n'est versionné
|
||||
[ ] La doc et les tests sont à jour
|
||||
```
|
||||
|
||||
### 8.2 Commandes utiles
|
||||
|
||||
```sh
|
||||
git switch -c feat/<sujet> # nouvelle branche
|
||||
git fetch origin && git rebase origin/main
|
||||
git log --oneline --graph --decorate # vue de l'historique
|
||||
git diff main...HEAD # relire tout son travail avant PR
|
||||
git rebase --interactive origin/main # nettoyer ses commits (branche perso)
|
||||
git push --force-with-lease # après rebase, sans risque pour autrui
|
||||
git tag -s v0.51.0 -m "release" # tag signé
|
||||
git shortlog -sn --no-merges # répartition des contributions
|
||||
```
|
||||
@@ -0,0 +1,94 @@
|
||||
# Maintainer: FWS <maintainers@nocode-var.tech>
|
||||
#
|
||||
# Arch package for the FWS kitty fork. Built with makepkg from this directory:
|
||||
#
|
||||
# cd packaging && makepkg -f
|
||||
#
|
||||
# The resulting fws-kitty-<version>-<rel>-<arch>.pkg.tar.zst is ready to be
|
||||
# added to a pacman repository (see README.md in this directory).
|
||||
#
|
||||
# kitty installs its own binary under /usr/bin and cannot coexist with the
|
||||
# upstream package, hence provides/conflicts.
|
||||
|
||||
pkgname=fws-kitty
|
||||
# Fork version from the version file: it names the release and the package.
|
||||
# The upstream kitty release built inside is tracked by _kittyver below.
|
||||
pkgver=0.1.17
|
||||
pkgrel=1
|
||||
pkgdesc='Fast, feature-rich, GPU based terminal (FWS fork with the file-manager kitten)'
|
||||
arch=('x86_64' 'aarch64')
|
||||
url='https://gitea.nocode-var.tech/FWS/FWS-Kitty'
|
||||
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.
|
||||
_branch=main
|
||||
_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=(
|
||||
python harfbuzz zlib libpng lcms2 xxhash openssl
|
||||
pixman cairo freetype2 fontconfig
|
||||
libx11 libxcb libxrandr libxinerama libxcursor libxi libxrender
|
||||
libxkbcommon libxkbcommon-x11 mesa wayland dbus
|
||||
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=(
|
||||
git go python pkgconf ncurses rsync which file simde shader-slang
|
||||
)
|
||||
optdepends=(
|
||||
'imagemagick: display uncommon image formats'
|
||||
'shader-slang: custom shaders'
|
||||
)
|
||||
provides=('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=(
|
||||
"$pkgname::git+$_repo#$_source_ref"
|
||||
"nerdfonts-symbols.tar.xz::https://github.com/ryanoasis/nerd-fonts/releases/download/v3.5.1/NerdFontsSymbolsOnly.tar.xz"
|
||||
)
|
||||
sha256sums=('SKIP' '01172f37db8543edb102e5cb5c64101c9f4686630804d49b419aa07b23a69996')
|
||||
|
||||
prepare() {
|
||||
# kitty embeds the mono variant of the Nerd font at build time, but Arch
|
||||
# only packages the proportional one, so ship the font with the build.
|
||||
mkdir -p "$pkgname/fonts"
|
||||
cp "$srcdir/SymbolsNerdFontMono-Regular.ttf" "$pkgname/fonts/"
|
||||
|
||||
cd "$pkgname"
|
||||
# linux-package regenerates the man pages and the HTML docs, and some of
|
||||
# their dependencies (furo, sphinx-design) are not packaged for Arch, so
|
||||
# keep a local throwaway environment instead of requiring the system ones.
|
||||
# Do not reuse the system packages: pip would then skip installing sphinx
|
||||
# itself and the venv would have no sphinx-build entry point.
|
||||
python -m venv .docs-venv
|
||||
.docs-venv/bin/pip install --disable-pip-version-check -q -r docs/requirements.txt
|
||||
}
|
||||
|
||||
package() {
|
||||
cd "$pkgname"
|
||||
# kitty's linux-package target stages a full self-contained install, so
|
||||
# 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"
|
||||
# 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"
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
# Paquet Arch — FWS-Kitty
|
||||
|
||||
Ce dossier contient le `PKGBUILD` qui produit le paquet pacman de FWS-Kitty,
|
||||
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
|
||||
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
|
||||
|
||||
```sh
|
||||
cd packaging
|
||||
makepkg -f # ajouter -s pour installer les dépendances manquantes
|
||||
```
|
||||
|
||||
Le résultat est `fws-kitty-<version>-<rel>-<arch>.pkg.tar.zst`.
|
||||
`makepkg` construit depuis la branche indiquée par `_branch` en haut du
|
||||
`PKGBUILD` (`main` par défaut). Pour publier une version précise, pointez-la
|
||||
sur un tag ou un commit :
|
||||
|
||||
```sh
|
||||
_branch=v0.50.0
|
||||
```
|
||||
|
||||
La police Symbols Nerd Font Mono n'est pas fournie par les dépôts Arch
|
||||
(`ttf-nerd-fonts-symbols` n'installe que la variante proportionnelle) : le
|
||||
`PKGBUILD` télécharge la release 3.5.1 de nerd-fonts et place le fichier dans
|
||||
`fonts/` avant la compilation.
|
||||
|
||||
La cible `linux-package` de kitty reconstruit aussi les pages de manuel et la
|
||||
documentation HTML : le `PKGBUILD` crée pour cela un environnement Python
|
||||
isolé dans `prepare()` et installe `docs/requirements.txt` (Sphinx, thème
|
||||
Furo…), car certaines de ces dépendances ne sont pas dans les dépôts Arch
|
||||
(`sphinx-design`, `furo` au nom `python-sphinx-furo`).
|
||||
|
||||
## Tester localement
|
||||
|
||||
```sh
|
||||
sudo pacman -U fws-kitty-*.pkg.tar.zst
|
||||
kitty --version
|
||||
kitten --version
|
||||
```
|
||||
|
||||
## Publier dans le dépôt pacman
|
||||
|
||||
Un dépôt pacman est un simple dossier HTTP contenant les paquets et une base
|
||||
`repo-add` :
|
||||
|
||||
```sh
|
||||
repo-add fws-kitty.db.tar.gz fws-kitty-*.pkg.tar.zst
|
||||
```
|
||||
|
||||
Puis, côté client, dans `/etc/pacman.conf` :
|
||||
|
||||
```ini
|
||||
[fws]
|
||||
SigLevel = Optional TrustAll
|
||||
Server = https://<hôte>/fws/$arch
|
||||
```
|
||||
|
||||
Le dossier doit être servi en HTTP/HTTPS statique (nginx, Caddy, GitHub/Gitea
|
||||
Pages…). Gitea n'a pas de registre pacman natif : le registre « Generic »
|
||||
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
|
||||
nginx (ou des assets de release) fournit directement.
|
||||
|
||||
## Publication automatique
|
||||
|
||||
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
|
||||
makepkg -f --nodeps # ou -s avec un utilisateur autorisé à pacman
|
||||
repo-add repo/fws-kitty.db.tar.gz fws-kitty-*.pkg.tar.zst
|
||||
# puis copier repo/ vers le serveur
|
||||
```
|
||||
|
||||
Le paquet ne contient pas les fichiers appartenant à `kitty-shell-integration`
|
||||
et `kitty-terminfo`. Ces paquets restent nécessaires pour l'utilisation de
|
||||
kitty et sont donc déclarés en dépendances.
|
||||
Loaded 100 of 109 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user