36 Commits
Author SHA1 Message Date
BlackAngelTV 5a1ba595f1 test(file-manager): stop the large directory filter test timing out the CI
CI / check (push) Successful in 4m58s
The 100ms bound on filtering 10000 entries is a wall clock measurement, and
it failed at 147ms in the release job while makepkg was still building next
to it, blocking the publication of the package for a test that guards
against a superlinear filter, not against a few milliseconds.

The limit is now one second, which still catches an implementation that
turns the listing into seconds, and the comment says why it is loose.
2026-12-03 11:31:11 +01:00
BlackAngelTV a142e0b596 chore(release): bump the fork version to 0.1.17
Release / release (push) Failing after 6m35s
CI / check (push) Successful in 4m56s
The 0.1.16 package was published before the changelog named each fork
release, so the version has to move for the documentation to reach the
packaged build. No functional change.
2026-12-03 11:23:05 +01:00
BlackAngelTV ee3f064886 docs(changelog): list the fork releases up to 0.1.16
CI / check (push) Successful in 3m58s
The changelog only had the accumulated list of the unreleased upstream
section, so a user of the fork could not tell which version brought which
fix, even though the package version is the fork one.

Each fork release from 0.1.10 to 0.1.16 now has its own entry naming the
change and the issue it closed, and the dock click tests are recorded in
0.1.16 next to the clipboard picker.
2026-12-03 11:20:54 +01:00
BlackAngelTV e39f938a39 Merge pull request 'test(docks): assert that a dock receives the clicks at any edge' (#59) from fix/dock-click-edge into main
CI / check (push) Successful in 2m20s
2026-12-03 11:02:13 +01:00
BlackAngelTV 408f16f798 test(docks): assert that a dock receives the clicks at any edge
CI / check (pull_request) Successful in 5m44s
The mouse handling of the docked windows had no test: the existing dock
tests only checked the regions the layout carves, and nothing checked
which window the clicks are routed to, so a click lost on a right dock
could not be caught by the test suite.

The two windows of a tab are now hit tested with their own areas, in both
orders, so the same point on a right dock and on a left dock must resolve
to the dock. The layout tests also pin the position of a right dock, which
previously only had its width and its containment checked.

Refs #44
2026-12-03 11:02:04 +01:00
BlackAngelTV 84f5500444 Merge pull request 'feat(clipboard): show the paste target and navigate the history picker' (#58) from feat/clipboard-history-picker into main
CI / check (push) Successful in 6m20s
Release / release (push) Successful in 9m58s
2026-12-03 11:01:28 +01:00
BlackAngelTV 43d01ab87e chore(release): bump the fork version to 0.1.16
CI / check (pull_request) Successful in 6m27s
2026-12-03 11:01:12 +01:00
BlackAngelTV 42c097c69a feat(clipboard): show the paste target and navigate the history picker
The clipboard history picker listed the entries without saying when they
were copied or which window would receive the paste, and the only way to
pick an entry was to read its hint label and type the letters, which the
picker never showed.

Each entry now carries the time it was copied and the window that will be
pasted into is named above the list, with a footer documenting the keys.
Pressing Up/Down moves the highlighted entry and Enter pastes it, through a
new --pick-from-list mode of the hints kitten that keeps the hint letters
working as before.

Fixes #49
2026-12-03 11:01:11 +01:00
BlackAngelTV 1b9e076139 Merge pull request 'feat(file-manager): handle the wheel, double clicks and right clicks' (#57) from feat/file-manager-mouse into main
CI / check (push) Successful in 2m14s
Release / release (push) Successful in 5m12s
2026-12-03 10:23:10 +01:00
BlackAngelTV e1cce67221 chore(release): bump the fork version to 0.1.15
CI / check (pull_request) Successful in 3m55s
The file manager gained mouse support, so cut a patch release. All the version
copies must agree for the packaging workflow.
2026-12-03 10:23:04 +01:00
BlackAngelTV 406bd726e2 feat(file-manager): handle the wheel, double clicks and right clicks
The panel only reacted to a left click on a row, so every other gesture was
keyboard-only: the wheel did nothing, a double click did not open the entry and
there was no way to reach the actions from the pointer. The wheel now steps the
selection by three rows without leaking the event to the hosting terminal, a
second click on the same row within kitty's click interval runs the primary
action, and a right click opens the action palette on the clicked row.

Fixes #47
2026-12-03 10:23:04 +01:00
BlackAngelTV 271babc8f1 Merge pull request 'fix(shortcuts): stop the shortcuts panel shadowing show_scrollback' (#56) from fix/help-shortcut-docs into main
CI / check (push) Canceled after 0s
Release / release (push) Canceled after 0s
2026-12-03 10:21:42 +01:00
BlackAngelTV 6e60b16e36 chore(release): bump the fork version to 0.1.14
CI / check (pull_request) Failing after 5m24s
The default shortcut of the shortcuts panel changed, so cut a patch release.
All the version copies must agree for the packaging workflow.
2026-12-03 10:21:39 +01:00
BlackAngelTV 365873b9bb fix(shortcuts): stop the shortcuts panel shadowing show_scrollback
The panel was bound to kitty_mod+h, the trigger upstream gives show_scrollback,
so the last definition won: Ctrl+Shift+H stopped browsing the scrollback in a
pager while the docs and the built-in help still announced that behavior. The
panel now uses kitty_mod+alt+h and the documentation follows, with a test that
fails when two default actions claim the same trigger.

Fixes #46
2026-12-03 10:21:38 +01:00
BlackAngelTV b994ccffce Merge pull request 'fix(search): give the in-place search a usable shortcut' (#55) from fix/search-shortcut into main
CI / check (push) Canceled after 0s
Release / release (push) Canceled after 0s
2026-12-03 10:21:04 +01:00
BlackAngelTV 474f1c0568 chore(release): bump the fork version to 0.1.13
CI / check (pull_request) Successful in 6m22s
The default shortcut of the in-place search changed, so cut a patch release.
All the version copies must agree for the packaging workflow.
2026-12-03 10:21:00 +01:00
BlackAngelTV 17462f5198 fix(search): give the in-place search a usable shortcut
kitty_mod+shift+f is the same physical key as kitty_mod+f, and
move_window_forward accepts the shifted fallback, so both definitions resolved
to the same trigger and the last one won: Ctrl+Shift+F moved the window instead
of opening the prompt, and the search had no shortcut at all. It now sits on
kitty_mod+alt+s, which no other default action claims.

Fixes #45
2026-12-03 10:21:00 +01:00
BlackAngelTV b036fb352e Merge pull request 'fix(help): keep the shortcuts panel inside its dock' (#54) from fix/help-action-column into main
CI / check (push) Failing after 6m32s
Release / release (push) Successful in 11m42s
2026-12-03 10:17:01 +01:00
BlackAngelTV f76eccc169 chore(release): bump the fork version to 0.1.12
CI / check (pull_request) Failing after 5m21s
The shortcuts panel now renders differently, so cut a patch release. All the
version copies must agree for the packaging workflow.
2026-12-03 10:16:57 +01:00
BlackAngelTV 801b4a2d89 fix(help): keep the shortcuts panel inside its dock
The action column of the panel was written with no width limit, so on a narrow
dock a long action name was cut by the edge of the panel in the middle of an
identifier, and a selected row padded with reverse video overflowed. The column
is now bounded by the room the row leaves and ellipsized with a single cell
ellipsis, the key column shrinks on very narrow docks, and the full name of the
selected action stays reachable on the help line.

Fixes #50
2026-12-03 10:16:57 +01:00
BlackAngelTV d83fbc71e3 Merge pull request 'feat(search): highlight the current match in its own color' (#53) from feat/search-current-match into main
Release / release (push) Canceled after 0s
CI / check (push) Failing after 5m5s
2026-12-03 10:06:07 +01:00
BlackAngelTV cbee630d4c chore(release): bump the fork version to 0.1.11
CI / check (pull_request) Successful in 10m3s
The scrollback search now renders differently, so cut a patch release. All the
version copies must agree for the packaging workflow.
2026-12-03 10:06:04 +01:00
BlackAngelTV 4df542f590 feat(search): highlight the current match in its own color
Every match of the in-place search used the same mark color, so after pressing
n or N the only hint of the current match was the counter in the window title,
which is easy to miss on a short query or a dense screen. The marker now colors
the current match with the second mark color and keeps the rest on the first
one, rebuilding the marker whenever the index changes.

Fixes #51
2026-12-03 10:06:04 +01:00
BlackAngelTV b406be9394 Merge pull request 'fix(search): allow searching for a literal \c or \r' (#52) from fix/search-literal-escapes into main
CI / check (push) Failing after 11m10s
Release / release (push) Successful in 16m16s
2026-12-03 10:01:53 +01:00
BlackAngelTV 4ca4a516ae chore(release): bump the fork version to 0.1.10
CI / check (pull_request) Failing after 11m10s
The search fix changes shipped behaviour, so cut a patch release. All the
version copies must agree for the packaging workflow.
2026-12-03 10:01:35 +01:00
BlackAngelTV f616651c49 fix(search): allow searching for a literal \c or \r
A query that starts with one of the two modifier prefixes could not be
escaped, so the text itself was unreachable: \c and \r were always consumed
as modifiers and the query ended up empty. A doubled backslash now ends the
modifier section and stands for the literal backslash, and the help line and
the docs document it.

Fixes #48
2026-12-03 10:01:34 +01:00
BlackAngelTV 1bd822b9e5 chore(release): bump the fork version to 0.1.9
CI / check (push) Successful in 4m17s
Release / release (push) Successful in 8m50s
The file manager fix changes shipped behaviour, so cut a patch release. All
the version copies must agree for the packaging workflow.
2026-11-26 10:17:44 +01:00
BlackAngelTV ce9f7ab974 docs(changelog): document the leader key and in-place scrollback search
Both features shipped without a changelog entry while every other feature of
this release had one. Also record the symlink and ~ handling of the file
manager.
2026-11-26 10:17:38 +01:00
BlackAngelTV 603ef78a6e fix(file-manager): browse symlinked directories and expand home
Symlinked directories were listed as files, so Enter opened them in the
editor instead of browsing them. Mappings and the remote control API reach
the panel without a shell, so --start-dir now expands a leading ~ itself.
Add the missing Python integration tests for the result handler.
2026-11-26 10:17:34 +01:00
BlackAngelTV f2f026c748 ci(release): allow for the index rebuild before checking the upload
CI / check (push) Successful in 4m33s
2026-11-25 21:44:17 +01:00
BlackAngelTV ec42571be5 chore(release): bump the fork version to 0.1.8
CI / check (push) Successful in 4m27s
Release / release (push) Failing after 6m37s
2026-11-25 21:35:07 +01:00
BlackAngelTV dea1771fe5 build(arch): skip the debug package the release never publishes
CI / check (push) Successful in 4m30s
2026-11-25 21:27:34 +01:00
BlackAngelTV 0cce80a6c5 style(docs): match the ruff format used by CI
CI / check (push) Successful in 3m22s
2026-11-25 21:17:35 +01:00
BlackAngelTV 70befe3802 ci(release): skip publishing an already published version
CI / check (push) Failing after 5s
2026-11-25 21:16:19 +01:00
BlackAngelTV a3d0fd38b7 docs(build): fix the Sphinx warnings and errors 2026-11-25 21:16:19 +01:00
BlackAngelTV 25840c6ce1 ci(release): keep a published version immutable
CI / check (push) Successful in 3m26s
The 0.1.7-1 release was built twice: the second run attached a package with a
different sha256 under the same name, so the CDN kept serving bytes from the
first build while the index announced the second, and pacman rejected the
download as an invalid or corrupted package. The release now refuses to replace
a published package whose checksum changed and asks for a pkgrel bump instead,
and it verifies the sha256 of the served file after the upload rather than only
its presence.
2026-11-25 20:58:40 +01:00
49 changed files with 1229 additions and 172 deletions

No files matched your search

+51 -7
View File
@@ -129,6 +129,29 @@ jobs:
tag="v$VERSION" tag="v$VERSION"
auth="Authorization: token $RELEASE_TOKEN" 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 ' release_id="$(curl -sS -H "$auth" "$api/releases/tags/$tag" | python3 -c '
import json, sys import json, sys
try: try:
@@ -178,6 +201,9 @@ jobs:
attach "$PACKAGE_FILE.sha256" "$PACKAGE_NAME.sha256" attach "$PACKAGE_FILE.sha256" "$PACKAGE_NAME.sha256"
- name: Push the package to repo.laxacube.ch - 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: env:
REPO_TOKEN: ${{ secrets.REPO_TOKEN }} REPO_TOKEN: ${{ secrets.REPO_TOKEN }}
PACKAGE_NAME: ${{ steps.package.outputs.name }} PACKAGE_NAME: ${{ steps.package.outputs.name }}
@@ -194,15 +220,33 @@ jobs:
-H 'Content-Type: application/octet-stream' \ -H 'Content-Type: application/octet-stream' \
--data-binary "@$PACKAGE_FILE" --data-binary "@$PACKAGE_FILE"
echo echo
# The index is rebuilt server-side, so wait for the package before # The index is rebuilt server-side and the file is served through a
# reporting success. # 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" url="https://repo.laxacube.ch/x86_64/$PACKAGE_NAME"
for _ in 1 2 3 4 5 6; do expected="$(cut -d' ' -f1 "$PACKAGE_FILE.sha256")"
if curl -fsSI "$url" > /dev/null; then code=000
echo "published $url" for _ in $(seq 1 24); do
exit 0 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 fi
sleep 5 sleep 5
done done
echo "::error::the upload was accepted but $url is not served yet" 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 exit 1
+5 -4
View File
@@ -10,7 +10,7 @@ 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 de commandes (`Ctrl+Shift+F3`) liste en direct toutes les actions, leur touche
et leur catégorie, y compris les actions sans raccourci. et leur catégorie, y compris les actions sans raccourci.
> **Aide rapide** : `Ctrl+Shift+H` (`kitty_mod+H`) ouvre le panneau latéral qui > **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, > liste tous les raccourcis, avec recherche et catégories. Dans le shell kitty,
> `help` fait la même chose. > `help` fait la même chose.
@@ -38,7 +38,7 @@ et leur catégorie, y compris les actions sans raccourci.
| `Ctrl+Shift+Alt+V` (`kitty_mod+alt+v`) | Colle une entrée de l'historique du presse-papiers. | | `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+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+R` (`kitty_mod+alt+r`) | Restaure la session enregistrée à la dernière fermeture de kitty. |
| `Ctrl+Shift+H` (`kitty_mod+H`) | Ouvre le panneau latéral de tous les raccourcis. | | `Ctrl+Shift+Alt+H` (`kitty_mod+alt+h`) | Ouvre le panneau latéral de tous les raccourcis. |
Deux fonctions FWS ne demandent aucune touche : Deux fonctions FWS ne demandent aucune touche :
@@ -81,7 +81,8 @@ Deux fonctions FWS ne demandent aucune touche :
| `Ctrl+Shift+X` | Va au prompt suivant. | | `Ctrl+Shift+X` | Va au prompt suivant. |
| `Ctrl+Shift+H` | Affiche tout l'historique dans un pager. | | `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+G` | Affiche la sortie de la dernière commande dans un pager. |
| `Ctrl+Shift+/` | Recherche dans l'historique. | | `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 ## Fenêtres
@@ -285,7 +286,7 @@ avec la syntaxe `map <touche> <action>`.
Dans le shell kitty (`Ctrl+Shift+Échap`), `help` sans argument ouvre un panneau 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 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 recherche rapide. Depuis un terminal : `kitty +kitten help` ; le raccourci
par défaut `Ctrl+Shift+H` (`kitty_mod+H`) ouvre le même panneau. par défaut `Ctrl+Shift+Alt+H` (`kitty_mod+alt+h`) ouvre le même panneau.
| Touche | Action | | Touche | Action |
| --- | --- | | --- | --- |
+8 -4
View File
@@ -302,7 +302,7 @@ _branch=feat/file-manager-panel
### Publication automatique ### Publication automatique
`version`, à la racine, est la source de vérité des releases. Il suit la version `version`, à la racine, est la source de vérité des releases. Il suit la version
du fork FWS (`0.1.7`), pas la version amont de kitty embarquée dans le paquet : 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 c'est elle qui nomme le tag, la release et le paquet
`fws-kitty-<version>-<rel>`. Il doit rester égal à `pkgver` dans `fws-kitty-<version>-<rel>`. Il doit rester égal à `pkgver` dans
`packaging/PKGBUILD` et à la version affichée par `fws-kitty` `packaging/PKGBUILD` et à la version affichée par `fws-kitty`
@@ -319,9 +319,13 @@ contrôles sur chaque PR et chaque push sur `main` qui ne modifie pas que
Pour reconstruire la même version du fork (correctif de packaging), incrémentez Pour reconstruire la même version du fork (correctif de packaging), incrémentez
`pkgrel` dans `packaging/PKGBUILD` puis lancez le workflow à la main `pkgrel` dans `packaging/PKGBUILD` puis lancez le workflow à la main
(*Actions → Release → Run workflow*) : le paquet `0.1.7-2` remplace alors le (*Actions → Release → Run workflow*) : le paquet `0.1.8-2` remplace alors le
`0.1.7-1`. Une nouvelle version du fork demande `version`, `pkgver` et les deux `0.1.8-1`. Une version déjà publiée n'est jamais réécrite avec un autre build :
front-ends, avec `pkgrel=1` ; pour suivre une nouvelle version de kitty, mettre 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 à jour `_kittyver` et `kitty/constants.py`. La publication vers
`repo.laxacube.ch` utilise le `repo.laxacube.ch` utilise le
secret `REPO_TOKEN` du dépôt, la release Gitea le secret `RELEASE_TOKEN` ; sans secret `REPO_TOKEN` du dépôt, la release Gitea le secret `RELEASE_TOKEN` ; sans
+24 -19
View File
@@ -12,29 +12,34 @@ window manager. The keyboard controls (which are :ref:`all customizable
Scrolling Scrolling
~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~
========================= ======================= ========================== =======================
Action Shortcut Action Shortcut
========================= ======================= ========================== =======================
Line up :sc:`scroll_line_up` (also :kbd:`⌥+⌘+⇞` and :kbd:`⌘+↑` on macOS) Line up :sc:`scroll_line_up` (also :kbd:`⌥+⌘+⇞` and :kbd:`⌘+↑` on macOS)
Line down :sc:`scroll_line_down` (also :kbd:`⌥+⌘+⇟` and :kbd:`⌘+↓` on macOS) Line down :sc:`scroll_line_down` (also :kbd:`⌥+⌘+⇟` and :kbd:`⌘+↓` on macOS)
Page up :sc:`scroll_page_up` (also :kbd:`⌘+⇞` on macOS) Page up :sc:`scroll_page_up` (also :kbd:`⌘+⇞` on macOS)
Page down :sc:`scroll_page_down` (also :kbd:`⌘+⇟` on macOS) Page down :sc:`scroll_page_down` (also :kbd:`⌘+⇟` on macOS)
Top :sc:`scroll_home` (also :kbd:`⌘+↖` on macOS) Top :sc:`scroll_home` (also :kbd:`⌘+↖` on macOS)
Bottom :sc:`scroll_end` (also :kbd:`⌘+↘` on macOS) Bottom :sc:`scroll_end` (also :kbd:`⌘+↘` on macOS)
Previous shell prompt :sc:`scroll_to_previous_prompt` (see :ref:`shell_integration`) Previous shell prompt :sc:`scroll_to_previous_prompt` (see :ref:`shell_integration`)
Next shell prompt :sc:`scroll_to_next_prompt` (see :ref:`shell_integration`) Next shell prompt :sc:`scroll_to_next_prompt` (see :ref:`shell_integration`)
Browse scrollback in less :sc:`show_scrollback` Browse scrollback in less :sc:`show_scrollback`
Browse last cmd output :sc:`show_last_command_output` (see :ref:`shell_integration`) Browse last cmd output :sc:`show_last_command_output` (see :ref:`shell_integration`)
Search scrollback in less :sc:`search_scrollback` (also :kbd:`⌘+F` on macOS) Search scrollback in less :sc:`search_scrollback` (also :kbd:`⌘+F` on macOS)
Search scrollback in place :sc:`search_scrollback_prompt` Search scrollback in place :sc:`search_scrollback_prompt`
========================= ======================= ========================== =======================
The in-place search highlights every match without replacing the screen with a The in-place search highlights every match without replacing the screen with a
pager. Prefix the query with ``\c`` to match case sensitively and with ``\r`` pager. It is bound to :kbd:`kitty_mod+alt+s` (:kbd:`Ctrl+Shift+Alt+S` by
to use a regular expression; both modifiers can be combined. While the search 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 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 :kbd:`Escape` ends it. The ``[current/total]`` counter is shown in the window
title and matches use the first marker color (see :opt:`mark1_foreground`). 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 The :ac:`scrollback_search_next`, :ac:`scrollback_search_prev` and
:ac:`clear_scrollback_search` actions can also be mapped directly. :ac:`clear_scrollback_search` actions can also be mapped directly.
+2 -2
View File
@@ -2,7 +2,7 @@ Installer kitty
======================== ========================
Installation des binaires Installation des binaires
---------------- -------------------------
.. highlight:: sh .. highlight:: sh
@@ -143,7 +143,7 @@ dossier d'installation. Pour désinstaller, il suffit de supprimer ce dossier.
Compiler depuis les sources Compiler depuis les sources
------------------------ ---------------------------
|kitty| est facile à compiler depuis les sources, suivez les :doc:`instructions |kitty| est facile à compiler depuis les sources, suivez les :doc:`instructions
<build>`. <build>`.
+2 -2
View File
@@ -146,7 +146,7 @@ Dépendances de compilation :
Compiler et exécuter depuis les sources avec Nix Compiler et exécuter depuis les sources avec Nix
------------------------------------------- ------------------------------------------------
Sous NixOS ou tout autre système Linux ou macOS disposant du gestionnaire de Sous NixOS ou tout autre système Linux ou macOS disposant du gestionnaire de
paquets Nix, exécutez `nix-shell paquets Nix, exécutez `nix-shell
@@ -163,7 +163,7 @@ votre plateforme ci-dessus.
.. _packagers: .. _packagers:
Notes pour les empaqueteurs Linux/macOS Notes pour les empaqueteurs Linux/macOS
---------------------------------- ---------------------------------------
Le code source publié de |kitty| est disponible sous forme de `tarball`_ depuis Le code source publié de |kitty| est disponible sous forme de `tarball`_ depuis
`la page des versions GitHub `la page des versions GitHub
+115 -1
View File
@@ -219,6 +219,78 @@ you use a decent Wayland compositor.
Detailed list of changes Detailed list of changes
------------------------------------- -------------------------------------
Fork FWS releases
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The versions below are the releases of the FWS fork, which carries its own
version so that a packaged build can be told apart from the upstream kitty it
is based on. Each entry names the issue it closed.
0.1.17 [2026-12-03]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
- The changelog now names each fork release with the issue it closed, instead
of leaving the fork changes in the accumulated upstream section. No
functional change.
0.1.16 [2026-12-03]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
- The clipboard history picker now shows when each entry was copied and the
title of the window the text will be pasted into, and :kbd:`↑`/:kbd:`↓` move
the highlighted entry so that :kbd:`Enter` pastes it without typing the
letters of a hint.
- The clicks of the docks are covered by tests: a left dock and a right dock
must both receive the clicks in their own area, and the layout tests pin the
position of a right dock instead of only its width.
0.1.15 [2026-12-03]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
- The :doc:`file manager <kittens/file-manager>` can be browsed with the mouse:
the wheel scrolls the list, a double click opens the entry under the pointer
like :kbd:`Enter`, and a right click opens the action palette on the clicked
row.
0.1.14 [2026-12-03]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
- :kbd:`Ctrl+Shift+H` browses the scrollback in a pager again with
:ac:`show_scrollback`: the keyboard shortcuts panel, which silently took the
key over while the documentation still promised the pager, moved to
:kbd:`Ctrl+Shift+Alt+H`.
0.1.13 [2026-12-03]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
- The in-place scrollback search got a usable default shortcut,
:kbd:`kitty_mod+alt+s`. It was bound to the same physical key as
:ac:`move_window_forward`, which allows the shifted fallback, so the last
definition won and the search never opened.
0.1.12 [2026-12-03]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
- The keyboard shortcuts panel keeps a long action name inside its own column,
shrinks its key column on very narrow docks so that a row always fits, and
shows the full name of the selected action on the help line, instead of
letting the edge of the dock cut the text.
0.1.11 [2026-12-03]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
- The current match of the in-place scrollback search is drawn with the second
mark color, so the match reached with :kbd:`n` and :kbd:`N` stands out from
the other ones without reading the window title.
0.1.10 [2026-12-03]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
- A literal :code:`\c` or :code:`\r` can be searched for by writing a doubled
backslash (:code:`\\c`, :code:`\\r`), instead of the query modifiers always
taking the prefix.
0.50.1 [unreleased] 0.50.1 [unreleased]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -235,7 +307,10 @@ Detailed list of changes
- kitty now keeps an in-memory history of the text copied to the clipboard, - 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` which :ac:`paste_from_clipboard_history` and :ac:`search_clipboard_history`
can paste back. Nothing is written to disk and private clipboard writes are can paste back. Nothing is written to disk and private clipboard writes are
never recorded. See :ref:`clipboard_history` for details. 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, - 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 in :file:`$XDG_STATE_HOME/kitty/last-session.json`, so that
@@ -263,6 +338,26 @@ Detailed list of changes
:kbd:`kitty_mod+H` is pressed. The panel can also be started with :kbd:`kitty_mod+H` is pressed. The panel can also be started with
:code:`kitty +kitten help`. :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 - 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 directory of the tab before its title, so the directory indicator of the tab
bar is visible without configuration. bar is visible without configuration.
@@ -273,6 +368,25 @@ Detailed list of changes
:doc:`accessibility guide </accessibility>` documents keyboard navigation and :doc:`accessibility guide </accessibility>` documents keyboard navigation and
the :opt:`text_fg_override_threshold` :code:`4.5 ratio` contrast mode. the :opt:`text_fg_override_threshold` :code:`4.5 ratio` contrast mode.
- The scrollback can now be searched in place: :ac:`search_scrollback_prompt`
highlights every match without opening the pager, shows the
:code:`[current/total]` counter in the window title and moves between matches
with :kbd:`n` and :kbd:`N`. Prefix the query with :code:`\c` for a case
sensitive search and :code:`\r` for a regular expression; write a doubled
backslash (:code:`\\c`, :code:`\\r`) to search for those prefixes literally.
The current match is drawn with the second mark color, so the match reached
with :kbd:`n` and :kbd:`N` is visible without looking at the window title.
See :doc:`basic` for the details.
- A configurable :opt:`leader` key now opens a which-key panel listing every
multi-key mapping available under that prefix, without waiting for a timeout.
The :doc:`command palette <kittens/command-palette>` shows the shortcut next
to each action and :kbd:`Ctrl+R` remaps it. See :ref:`leader_keymap`.
- The :doc:`file manager <kittens/file-manager>` now follows symbolic links to
directories, so they can be browsed like real ones, and expands a leading
:code:`~` in :code:`--start-dir`.
- A new :doc:`file manager kitten <kittens/file-manager>`, run with - A new :doc:`file manager kitten <kittens/file-manager>`, run with
:code:`kitten file-manager`, that browses directories in a side panel and :code:`kitten file-manager`, that browses directories in a side panel and
changes the working directory of the shell that launched it without leaving changes the working directory of the shell that launched it without leaving
+4 -2
View File
@@ -276,8 +276,10 @@ instance, newest first, and lets you paste one of them back with
:ac:`paste_from_clipboard_history`. :ac:`search_clipboard_history` filters the :ac:`paste_from_clipboard_history`. :ac:`search_clipboard_history` filters the
history with a fuzzy query before showing the list. history with a fuzzy query before showing the list.
The picker numbers the entries: type the number next to the entry you want to The picker lists the entries with the time each one was copied and names the
paste, or press :kbd:`Escape` to cancel. 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 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 when kitty exits and secrets copied during a session do not outlive it. Text
+12 -6
View File
@@ -20,7 +20,7 @@ from docutils import nodes
from docutils.parsers.rst.roles import normalize_options from docutils.parsers.rst.roles import normalize_options
from pygments.lexer import RegexLexer from pygments.lexer import RegexLexer
from pygments.lexer import bygroups as untyped_bygroups from pygments.lexer import bygroups as untyped_bygroups
from pygments.token import Comment, Error, Keyword, Literal, Name, Number, String, Whitespace from pygments.token import Comment, Error, Keyword, Literal, Name, Number, Punctuation, String, Whitespace
from sphinx import addnodes, version_info from sphinx import addnodes, version_info
from sphinx.util.logging import getLogger from sphinx.util.logging import getLogger
@@ -220,15 +220,19 @@ def commit_role(
name: str, rawtext: str, text: str, lineno: int, inliner: Any, options: Any = {}, content: Any = [] name: str, rawtext: str, text: str, lineno: int, inliner: Any, options: Any = {}, content: Any = []
) -> Tuple[List[nodes.reference], List[nodes.problematic]]: ) -> Tuple[List[nodes.reference], List[nodes.problematic]]:
"Link to a github commit" "Link to a github commit"
# The changelog also cites upstream kitty commits, which a shallow clone of
# the fork does not contain: link to the id as written instead of failing
# the documentation build over missing local history.
try: try:
commit_id = subprocess.check_output(f'git rev-list --max-count=1 {text}'.split()).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: except Exception:
msg = inliner.reporter.error(f'git commit id "{text}" not recognized.', line=lineno) commit_id = text
prb = inliner.problematic(rawtext, rawtext, msg)
return [prb], [msg]
url = f'https://github.com/kovidgoyal/kitty/commit/{commit_id}' url = f'https://github.com/kovidgoyal/kitty/commit/{commit_id}'
options = normalize_options(options) options = normalize_options(options)
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) node = nodes.reference(rawtext, f'commit: {short_id}', refuri=url, **options)
return [node], [] return [node], []
@@ -507,6 +511,8 @@ class ConfLexer(RegexLexer):
tokens = { tokens = {
'root': [ 'root': [
(r'#.*?$', Comment.Single), (r'#.*?$', Comment.Single),
# Closing brace of a profile block, see :ref:`config-profiles`.
(r'\}', Punctuation),
(r'\s+$', Whitespace), (r'\s+$', Whitespace),
(r'\s+', Whitespace), (r'\s+', Whitespace),
(r'(include)(\s+)(.+?)$', bygroups(Comment.Preproc, Whitespace, Name.Namespace)), (r'(include)(\s+)(.+?)$', bygroups(Comment.Preproc, Whitespace, Name.Namespace)),
+6 -2
View File
@@ -100,12 +100,16 @@ quand même avec le reste de la configuration.
Les profils ne peuvent pas être imbriqués. Ils peuvent toutefois utiliser Les profils ne peuvent pas être imbriqués. Ils peuvent toutefois utiliser
:code:`include` et les autres directives d'inclusion. :code:`include` et les autres directives d'inclusion.
.. envvar:: KITTY_PROFILE
Nom du profil à activer au démarrage, voir :ref:`config-profiles`.
.. include:: /generated/conf-kitty.rst .. include:: /generated/conf-kitty.rst
Exemple de kitty.conf Exemple de kitty.conf
-------------------- ---------------------
.. only:: html .. only:: html
@@ -129,7 +133,7 @@ Cela affichera le fichier de configuration par défaut commenté sur
:file:`STDOUT`. :file:`STDOUT`.
Toutes les actions associables Toutes les actions associables
------------------------ ------------------------------
Voir la :doc:`liste de tout ce que vous pouvez faire faire à |kitty| </actions>`. Voir la :doc:`liste de tout ce que vous pouvez faire faire à |kitty| </actions>`.
+3 -3
View File
@@ -83,10 +83,10 @@ Glossaire
.. _env_vars: .. _env_vars:
Variables d'environnement Variables d'environnement
------------------------ -------------------------
Variables qui influencent le comportement de kitty Variables qui influencent le comportement de kitty
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. envvar:: KITTY_CONFIG_DIRECTORY .. envvar:: KITTY_CONFIG_DIRECTORY
@@ -167,7 +167,7 @@ Variables qui influencent le comportement de kitty
Variables que kitty définit en lançant des programmes enfants Variables que kitty définit en lançant des programmes enfants
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. envvar:: LANG .. envvar:: LANG
+1 -1
View File
@@ -1,7 +1,7 @@
:orphan: :orphan:
L'interface en ligne de commande de kitty L'interface en ligne de commande de kitty
==================================== =========================================
.. program:: kitty .. program:: kitty
+18 -2
View File
@@ -27,7 +27,8 @@ Il peut aussi tourner dans un :doc:`panneau du bureau </kittens/panel>` ou dans
n'importe quelle :term:`fenêtre kitty <window>` classique. n'importe quelle :term:`fenêtre kitty <window>` classique.
Le répertoire de départ est celui de la fenêtre courante, sauf si un répertoire Le répertoire de départ est celui de la fenêtre courante, sauf si un répertoire
est passé en argument ou avec ``--start-dir``. 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:: .. note::
@@ -61,7 +62,9 @@ Actions
:kbd:`→` ou :kbd:`L` :kbd:`→` ou :kbd:`L`
descend dans le répertoire sélectionné ; le shell y va aussi, au prompt descend dans le répertoire sélectionné ; le shell y va aussi, au prompt
suivant, quand la synchronisation est active. suivant, quand la synchronisation est active. Un lien symbolique vers un
répertoire se parcourt comme un répertoire ; un lien cassé reste une entrée
ordinaire, ouverte dans l'éditeur.
:kbd:`←`, :kbd:`Retour arrière` ou :kbd:`H` :kbd:`←`, :kbd:`Retour arrière` ou :kbd:`H`
remonte au répertoire parent. remonte au répertoire parent.
@@ -158,6 +161,16 @@ pas soumise.
synchronisation reste inerte. synchronisation reste inerte.
Souris
------
Le panneau se pilote aussi à la souris. La molette parcourt la liste par pas de
trois lignes, sans transmettre l'événement au terminal qui héberge le dock. Un
double-clic ouvre l'entrée sous le pointeur, comme :kbd:`Entrée` : un répertoire
est parcouru, un fichier est confié à l'éditeur. Un clic droit ouvre la palette
d'actions sur la ligne cliquée, identique au raccourci :kbd:`:`.
.. _file-manager-shortcuts: .. _file-manager-shortcuts:
Raccourcis et configuration Raccourcis et configuration
@@ -232,6 +245,9 @@ Limites
pour changer de répertoire ; utilisez-le depuis une fenêtre de shell. pour changer de répertoire ; utilisez-le depuis une fenêtre de shell.
- Le panneau ne suit pas les modifications faites par d'autres programmes : - Le panneau ne suit pas les modifications faites par d'autres programmes :
utilisez :kbd:`Ctrl+R` pour relire le répertoire. utilisez :kbd:`Ctrl+R` pour relire le répertoire.
- Les liens symboliques ne sont pas distingués des fichiers ordinaires dans
l'affichage : seul le fait qu'ils pointent vers un répertoire change leur
comportement à l'ouverture.
.. include:: /generated/conf-kitten-file_manager.rst .. include:: /generated/conf-kitten-file_manager.rst
+5 -4
View File
@@ -6,14 +6,15 @@ Panneau d'aide aux raccourcis
Le panneau d'aide affiche tous les raccourcis clavier actifs, triés par 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 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 gestionnaire de fichiers, et reste en lecture seule : :kbd:`Entrée` ne déclenche
aucune action. Il est mappé sur :kbd:`kitty_mod+H` (:kbd:`Ctrl+Shift+H` par aucune action. Il est mappé sur :kbd:`kitty_mod+alt+h`
défaut). (:kbd:`Ctrl+Shift+Alt+H` par défaut), pour laisser :kbd:`kitty_mod+h` à
:ac:`show_scrollback`.
Utilisation Utilisation
----------- -----------
Dans le :doc:`shell kitty </shell>` (:kbd:`Ctrl+Shift+Échap`), la commande Dans le :doc:`shell kitty </remote-control>` (:kbd:`Ctrl+Shift+Échap`), la commande
``help`` sans argument ouvre le panneau, tout comme :kbd:`kitty_mod+H` dans ``help`` sans argument ouvre le panneau, tout comme :kbd:`kitty_mod+alt+h` dans
n'importe quelle fenêtre :: n'importe quelle fenêtre ::
help help
+1 -1
View File
@@ -1,7 +1,7 @@
.. _kittens: .. _kittens:
Étendre avec les kittens Étendre avec les kittens
----------------------- ------------------------
.. toctree:: .. toctree::
:hidden: :hidden:
+3 -3
View File
@@ -124,7 +124,7 @@ Par exemple ::
.. _watchers: .. _watchers:
Surveiller les fenêtres lancées Surveiller les fenêtres lancées
--------------------------- -------------------------------
L'option :option:`launch --watcher` vous permet d'indiquer des fonctions Python L'option :option:`launch --watcher` vous permet d'indiquer des fonctions Python
qui seront appelées lors d'événements précis, comme le redimensionnement ou la qui seront appelées lors d'événements précis, comme le redimensionnement ou la
@@ -238,7 +238,7 @@ de contrôle à distance à votre disposition.
Recherche des exécutables Recherche des exécutables
----------------------- -------------------------
Lorsque vous indiquez une commande à exécuter sous forme de simple nom plutôt Lorsque vous indiquez une commande à exécuter sous forme de simple nom plutôt
que de chemin absolu, elle est recherchée dans la variable d'environnement que de chemin absolu, elle est recherchée dans la variable d'environnement
@@ -252,6 +252,6 @@ shell est utilisée.
Voir :opt:`exe_search_path` pour les détails et la façon de contrôler cela. Voir :opt:`exe_search_path` pour les détails et la façon de contrôler cela.
Référence de syntaxe Référence de syntaxe
------------------ --------------------
.. include:: /generated/launch.rst .. include:: /generated/launch.rst
+1 -1
View File
@@ -467,7 +467,7 @@ All mappable actions
There is a list of :doc:`all mappable actions <actions>`. There is a list of :doc:`all mappable actions <actions>`.
Remapping from the command palette Remapping from the command palette
--------------------------------- ----------------------------------
Every entry in the command palette shows the shortcut currently bound to it. 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 Select an action and press :kbd:`Ctrl+R` to remap it: the footer asks for the
+4 -4
View File
@@ -1,5 +1,5 @@
Marquer du texte à l'écran Marquer du texte à l'écran
--------------------- --------------------------
kitty peut marquer du texte à l'écran à partir d'expressions régulières. C'est kitty peut marquer du texte à l'écran à partir d'expressions régulières. C'est
@@ -67,7 +67,7 @@ Vous pouvez aussi utiliser les facilités de :doc:`contrôle à distance
Défiler jusqu'aux marques Défiler jusqu'aux marques
-------------------- -------------------------
kitty dispose d'une action :ac:`scroll_to_mark` pour défiler jusqu'à la ligne kitty dispose d'une action :ac:`scroll_to_mark` pour défiler jusqu'à la ligne
suivante contenant une marque. Vous pouvez l'utiliser en l'associant à un suivante contenant une marque. Vous pouvez l'utiliser en l'associant à un
@@ -88,7 +88,7 @@ Ce qui ne défilera que vers les marques de type 1.
La syntaxe complète pour créer des marques La syntaxe complète pour créer des marques
------------------------------------- ------------------------------------------
La syntaxe de l'action :ac:`toggle_marker` est :: La syntaxe de l'action :ac:`toggle_marker` est ::
@@ -105,7 +105,7 @@ Ici :code:`marker-type` vaut l'un des suivants :
.. _marker_funcs: .. _marker_funcs:
Fonctions de marqueur arbitraires Fonctions de marqueur arbitraires
----------------------------- ---------------------------------
Vous pouvez créer vos propres fonctions de marqueur. Créez un fichier Python Vous pouvez créer vos propres fonctions de marqueur. Créez un fichier Python
nommé :file:`mymarker.py` et, à l'intérieur, une fonction :code:`marker`. Cette nommé :file:`mymarker.py` et, à l'intérieur, une fonction :code:`marker`. Cette
+1 -1
View File
@@ -90,7 +90,7 @@ ci-dessous :
.. _matching_criteria: .. _matching_criteria:
Critères de correspondance Critères de correspondance
------------------ --------------------------
Une entrée de :file:`open-actions.conf` doit avoir un ou plusieurs critères de Une entrée de :file:`open-actions.conf` doit avoir un ou plusieurs critères de
correspondance. Les URL qui satisfont tous les critères d'une entrée déclenchent correspondance. Les URL qui satisfont tous les critères d'une entrée déclenchent
+11 -10
View File
@@ -52,7 +52,7 @@ les détails.
.. _layouts: .. _layouts:
Dispositions Dispositions
---------- ------------
Une :term:`disposition <layout>` est un agencement de plusieurs Une :term:`disposition <layout>` est un agencement de plusieurs
:term:`fenêtres kitty <window>` à l'intérieur d'une :term:`fenêtre OS :term:`fenêtres kitty <window>` à l'intérieur d'une :term:`fenêtre OS
@@ -130,7 +130,7 @@ sur le contrôle à distance.
Contrôle à distance Contrôle à distance
------------------ -------------------
|kitty| dispose d'un système très puissant qui vous permet de le piloter |kitty| dispose d'un système très puissant qui vous permet de le piloter
depuis :doc:`l'invite du shell, même via SSH <remote-control>`. Vous pouvez depuis :doc:`l'invite du shell, même via SSH <remote-control>`. Vous pouvez
@@ -159,7 +159,7 @@ facilement d'une session à l'autre avec une combinaison de touches. Voir
Créer des onglets et des fenêtres Créer des onglets et des fenêtres
------------------------------- ---------------------------------
kitty peut exécuter des programmes arbitraires dans de nouveaux :term:`onglets kitty peut exécuter des programmes arbitraires dans de nouveaux :term:`onglets
<tab>`, :term:`fenêtres <window>` ou :term:`surcouches <overlay>` sur une <tab>`, :term:`fenêtres <window>` ou :term:`surcouches <overlay>` sur une
@@ -172,7 +172,7 @@ combinaison de touches. Pour apprendre comment faire, voir :doc:`ici <launch>`.
Fonctionnalités de la souris Fonctionnalités de la souris
------------------- ----------------------------
* Vous pouvez cliquer sur une URL pour l'ouvrir dans un navigateur. * Vous pouvez cliquer sur une URL pour l'ouvrir dans un navigateur.
* Vous pouvez double-cliquer pour sélectionner un mot, puis glisser pour * Vous pouvez double-cliquer pour sélectionner un mot, puis glisser pour
@@ -233,7 +233,7 @@ de nouveaux onglets, ou double-cliquer sur un onglet existant pour le renommer.
open_actions open_actions
Contrôle des polices Contrôle des polices
----------------- --------------------
|kitty| dispose de fonctionnalités de sélection de polices extrêmement |kitty| dispose de fonctionnalités de sélection de polices extrêmement
souples et puissantes. Vous pouvez indiquer des familles individuelles pour souples et puissantes. Vous pouvez indiquer des familles individuelles pour
@@ -252,7 +252,7 @@ Le tampon d'historique
|kitty| prend en charge le défilement arrière pour consulter l'historique, |kitty| prend en charge le défilement arrière pour consulter l'historique,
comme la plupart des terminaux. Vous pouvez utiliser les raccourcis clavier ou comme la plupart des terminaux. Vous pouvez utiliser les raccourcis clavier ou
la molette de la souris. |kitty| affiche une :opt:`barre de défilement` la molette de la souris. |kitty| affiche une :opt:`scrollbar`
interactive le long du bord droit de la fenêtre, qui montre votre position interactive le long du bord droit de la fenêtre, qui montre votre position
actuelle dans l'historique. Vous pouvez cliquer et faire glisser la barre de actuelle dans l'historique. Vous pouvez cliquer et faire glisser la barre de
défilement pour naviguer rapidement dans l'historique. défilement pour naviguer rapidement dans l'historique.
@@ -267,12 +267,13 @@ formatage du texte sont préservés. Vous pouvez explorer confortablement le
tampon d'historique dans le pager. tampon d'historique dans le pager.
De plus, vous pouvez envoyer le contenu du tampon d'historique à une commande De plus, vous pouvez envoyer le contenu du tampon d'historique à une commande
arbitraire exécutée dans une nouvelle :term:`fenêtre`, un nouvel :term:`onglet` arbitraire exécutée dans une nouvelle :term:`fenêtre <window>`, un nouvel
ou une :term:`surcouche`. Par exemple :: :term:`onglet <tab>` ou une :term:`surcouche <overlay>`. Par exemple ::
map f1 launch --stdin-source=@screen_scrollback --stdin-add-formatting less +G -R map f1 launch --stdin-source=@screen_scrollback --stdin-add-formatting less +G -R
ouvrira le tampon d'historique dans une nouvelle :term:`fenêtre` lorsque vous 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>` appuyez sur la touche :kbd:`F1`. Voir :sc:`show_scrollback <show_scrollback>`
pour les détails. pour les détails.
@@ -307,7 +308,7 @@ les détails.
.. _cpbuf: .. _cpbuf:
Plusieurs tampons de copier/coller Plusieurs tampons de copier/coller
----------------------------- ----------------------------------
En plus du copier/coller depuis le presse-papiers du système, vous pouvez En plus du copier/coller depuis le presse-papiers du système, vous pouvez
configurer dans |kitty| un nombre arbitraire de tampons de copier/coller. Pour configurer dans |kitty| un nombre arbitraire de tampons de copier/coller. Pour
+2 -2
View File
@@ -30,7 +30,7 @@ d'énergie pour les tâches courantes, la latence entre le clavier et l'écran,
le débit (traitement de grandes quantités de données). le débit (traitement de grandes quantités de données).
Latence entre le clavier et l'écran Latence entre le clavier et l'écran
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Elle se mesure soit avec du matériel dédié, soit avec des logiciels comme Elle se mesure soit avec du matériel dédié, soit avec des logiciels comme
`Typometer <https://pavelfatin.com/typometer/>`__. Les mesures de tiers `Typometer <https://pavelfatin.com/typometer/>`__. Les mesures de tiers
@@ -122,7 +122,7 @@ d'échappement de formatage typiques et de texte uniquement ASCII.
Consommation d'énergie Consommation d'énergie
^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^
Malheureusement, je n'ai pas l'infrastructure pour mesurer la consommation Malheureusement, je n'ai pas l'infrastructure pour mesurer la consommation
d'énergie réelle, l'utilisation du processeur devra donc la représenter. Voici d'énergie réelle, l'utilisation du processeur devra donc la représenter. Voici
+1 -1
View File
@@ -1,5 +1,5 @@
Soutenez le développement de kitty ❤️ Soutenez le développement de kitty ❤️
============================== =====================================
Mon objectif avec |kitty| est de faire avancer l'écosystème stagnant des Mon objectif avec |kitty| est de faire avancer l'écosystème stagnant des
terminaux. Dans cette optique, kitty possède de nombreuses fonctionnalités terminaux. Dans cette optique, kitty possède de nombreuses fonctionnalités
+71 -16
View File
@@ -220,28 +220,57 @@ type displayLine struct {
const maxKeyDisplayWidth = 30 const maxKeyDisplayWidth = 30
// keyWidthFor is the number of cells reserved for the key itself. On a very
// narrow panel it shrinks, so that the action column still has room and the row
// never extends past the edge of the panel.
func keyWidthFor(panelWidth int) int {
return min(maxKeyDisplayWidth, max(panelWidth-10, 1))
}
// keyColumnWidthFor is the number of cells the key column takes: the four space
// indent, the padded key and the separating space.
func keyColumnWidthFor(panelWidth int) int {
return 4 + keyWidthFor(panelWidth) + 1
}
// unmappedLabel is shown in the key column for actions with no keyboard shortcut. // unmappedLabel is shown in the key column for actions with no keyboard shortcut.
const unmappedLabel = "(unmapped)" const unmappedLabel = "(unmapped)"
// truncateToWidth truncates s to fit within maxWidth cells, appending "..." if // ellipsis marks a truncated string. It is a single cell, so that as much of the
// truncated and maxWidth > 3. When maxWidth <= 3, the string is simply trimmed // original text as possible is kept inside the panel.
// to fit without appending ellipsis (no room for it). 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 { func truncateToWidth(s string, maxWidth int) string {
if wcswidth.Stringwidth(s) <= maxWidth { if wcswidth.Stringwidth(s) <= maxWidth {
return s return s
} }
ellipsisWidth := wcswidth.Stringwidth(ellipsis)
runes := []rune(s) runes := []rune(s)
if maxWidth <= 3 { if maxWidth <= ellipsisWidth {
// Not enough room for ellipsis; just trim to fit // Not enough room for the ellipsis; just trim to fit
for len(runes) > 0 && wcswidth.Stringwidth(string(runes)) > maxWidth { for len(runes) > 0 && wcswidth.Stringwidth(string(runes)) > maxWidth {
runes = runes[:len(runes)-1] runes = runes[:len(runes)-1]
} }
return string(runes) return string(runes)
} }
for len(runes) > 0 && wcswidth.Stringwidth(string(runes))+3 > maxWidth { for len(runes) > 0 && wcswidth.Stringwidth(string(runes))+ellipsisWidth > maxWidth {
runes = runes[:len(runes)-1] 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 ─────────". // sectionHeader returns a separator line like " ── label ─────────".
@@ -642,11 +671,22 @@ func (h *Handler) draw_screen() {
h.drawFlatResults(resultsStartY, resultsHeight, width) 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) h.lp.MoveCursorTo(1, helpY)
if b := h.selectedBinding(); b != nil && b.Help != "" { if b := h.selectedBinding(); b != nil {
helpStr := truncateToWidth(b.Help, max(width-2, 3)) detail := b.Help
h.lp.QueueWriteString(h.lp.SprintStyled("dim italic", " "+helpStr)) 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 // Draw key hints footer
@@ -863,8 +903,9 @@ func (h *Handler) drawBindingLine(filteredIdx, width int, isSelected bool) {
b := &h.all_items[idx].binding b := &h.all_items[idx].binding
actionDisplay := h.all_items[idx].actionText actionDisplay := h.all_items[idx].actionText
// Build the key display // Build the key display, bounded by the room the panel leaves as well
keyDisplay := keyDisplayText(b) keyWidth := keyWidthFor(width)
keyDisplay := truncateToWidth(keyDisplayText(b), keyWidth)
// Determine match info for highlighting (only set when a query is active) // Determine match info for highlighting (only set when a query is active)
var mi *matchInfo var mi *matchInfo
@@ -893,8 +934,8 @@ func (h *Handler) drawBindingLine(filteredIdx, width int, isSelected bool) {
return s return s
} }
// Render key column (4-space indent + key padded to maxKeyDisplayWidth + space) // Render key column (4-space indent + key padded to the key column width)
paddingLen := max(0, maxKeyDisplayWidth-wcswidth.Stringwidth(keyDisplay)) paddingLen := max(0, keyWidth-wcswidth.Stringwidth(keyDisplay))
pad := strings.Repeat(" ", paddingLen) + " " pad := strings.Repeat(" ", paddingLen) + " "
ks := keyStyle ks := keyStyle
if b.Key == "" { if b.Key == "" {
@@ -908,7 +949,8 @@ func (h *Handler) drawBindingLine(filteredIdx, width int, isSelected bool) {
h.lp.QueueWriteString(h.lp.SprintStyled(ks, " "+keyDisplay+pad)) h.lp.QueueWriteString(h.lp.SprintStyled(ks, " "+keyDisplay+pad))
} }
// Render action display column // 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 { if mi != nil && len(mi.actionPositions) > 0 {
h.lp.QueueWriteString(h.highlightMatchedChars(actionDisplay, mi.actionPositions, baseStyle, matchStyle)) h.lp.QueueWriteString(h.highlightMatchedChars(actionDisplay, mi.actionPositions, baseStyle, matchStyle))
} else { } else {
@@ -932,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 // rowToFilteredIdx converts a 0-indexed cell Y coordinate to a filtered item
// index, or -1 if the cell is not over a clickable item. Internally converts // index, or -1 if the cell is not over a clickable item. Internally converts
// to 1-indexed screen rows (matching the MoveCursorTo convention) to compare // to 1-indexed screen rows (matching the MoveCursorTo convention) to compare
+69 -7
View File
@@ -7,6 +7,7 @@ import (
"testing" "testing"
"github.com/kovidgoyal/kitty/tools/tui/loop" "github.com/kovidgoyal/kitty/tools/tui/loop"
"github.com/kovidgoyal/kitty/tools/wcswidth"
) )
// testBinding creates a Binding where Action, ActionDisplay, and Definition all // testBinding creates a Binding where Action, ActionDisplay, and Definition all
@@ -435,13 +436,13 @@ func TestTruncateToWidth(t *testing.T) {
t.Fatalf("Expected %q unchanged at exact width, got %q", "hello", got) t.Fatalf("Expected %q unchanged at exact width, got %q", "hello", got)
} }
// Over width: truncated with ellipsis // Over width: truncated with a single cell ellipsis
got = truncateToWidth("hello world", 8) got = truncateToWidth("hello world", 8)
if !strings.HasSuffix(got, "...") { if !strings.HasSuffix(got, ellipsis) {
t.Fatalf("Expected truncated string to end with '...', got %q", got) t.Fatalf("Expected truncated string to end with %q, got %q", ellipsis, got)
} }
if len([]rune(got)) > 8 { if wcswidth.Stringwidth(got) > 8 {
t.Fatalf("Expected truncated string to be at most 8 runes, got %d in %q", len([]rune(got)), got) 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 // Long key like a mouse binding should be truncated
@@ -450,8 +451,69 @@ func TestTruncateToWidth(t *testing.T) {
if len([]rune(got)) > maxKeyDisplayWidth { if len([]rune(got)) > maxKeyDisplayWidth {
t.Fatalf("Key should be truncated to maxKeyDisplayWidth, got len=%d: %q", len([]rune(got)), got) t.Fatalf("Key should be truncated to maxKeyDisplayWidth, got len=%d: %q", len([]rune(got)), got)
} }
if !strings.HasSuffix(got, "...") { if !strings.HasSuffix(got, ellipsis) {
t.Fatalf("Truncated key should end with '...', got %q", got) 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))
} }
} }
+86 -3
View File
@@ -80,7 +80,17 @@ func read_dir(dir string, show_hidden bool, sort_by string) ([]Entry, error) {
continue continue
} }
e := Entry{Name: name, IsDir: item.IsDir()} e := Entry{Name: name, IsDir: item.IsDir()}
if info, ierr := item.Info(); ierr == nil { info, ierr := item.Info()
if item.Type()&os.ModeSymlink != 0 {
// A symlink is reported as its own type, so a link to a directory
// would be opened in the editor instead of being browsed. Follow
// it to classify the entry; broken links stay plain entries.
if target, terr := os.Stat(filepath.Join(dir, name)); terr == nil {
info, ierr = target, nil
e.IsDir = target.IsDir()
}
}
if ierr == nil {
e.ModTime = info.ModTime().Unix() e.ModTime = info.ModTime().Unix()
e.Size = info.Size() e.Size = info.Size()
} }
@@ -90,6 +100,23 @@ func read_dir(dir string, show_hidden bool, sort_by string) ([]Entry, error) {
return entries, nil return entries, nil
} }
// expand_home expands a leading ~ so that a directory given in a mapping or by
// the remote control API, where no shell expands it, names the same directory
// as it would on the command line.
func expand_home(path string) (string, error) {
if path != "~" && !strings.HasPrefix(path, "~/") {
return path, nil
}
home, err := os.UserHomeDir()
if err != nil {
return "", err
}
if path == "~" {
return home, nil
}
return filepath.Join(home, path[2:]), nil
}
func entry_path(dir, name string) string { func entry_path(dir, name string) string {
return filepath.Join(dir, name) return filepath.Join(dir, name)
} }
@@ -169,6 +196,10 @@ func resolve_start_dir(candidate string) (string, error) {
} }
candidate = cwd candidate = cwd
} }
candidate, err := expand_home(candidate)
if err != nil {
return "", err
}
abs, err := filepath.Abs(candidate) abs, err := filepath.Abs(candidate)
if err != nil { if err != nil {
return "", err return "", err
@@ -197,6 +228,28 @@ func truncate_to_width(s string, max_width int) string {
return string(runes) + "\u2026" return string(runes) + "\u2026"
} }
// wheel_scroll_lines is the number of rows one wheel notch scrolls. It sits
// between a single line, which makes a long directory tedious, and the default
// kitty wheel_scroll_multiplier of five, which skips too much in a panel.
const wheel_scroll_lines = 3
// double_click_interval is the largest gap between two clicks on the same row
// that still counts as a double click, matching kitty's click_interval default.
const double_click_interval = 500 * time.Millisecond
// click_tracker remembers the last click so that a second click on the same row
// opens it, while clicks on different rows stay single selections.
type click_tracker struct {
at time.Time
idx int
}
func (c *click_tracker) is_double(now time.Time, idx int) bool {
prev_at, prev_idx := c.at, c.idx
c.at, c.idx = now, idx
return idx == prev_idx && !prev_at.IsZero() && now.Sub(prev_at) <= double_click_interval
}
type Handler struct { type Handler struct {
lp *loop.Loop lp *loop.Loop
screen_size loop.ScreenSize screen_size loop.ScreenSize
@@ -224,6 +277,7 @@ type Handler struct {
sync *shell_sync sync *shell_sync
sync_handled bool sync_handled bool
sync_published bool sync_published bool
clicks click_tracker
} }
func (h *Handler) initialize() (string, error) { func (h *Handler) initialize() (string, error) {
@@ -1057,13 +1111,42 @@ func (h *Handler) row_to_entry(cell_y int) int {
} }
func (h *Handler) on_mouse_event(ev *loop.MouseEvent) error { func (h *Handler) on_mouse_event(ev *loop.MouseEvent) error {
// The palette owns the pointer while it is open, so clicks and wheel events
// do not change the selection behind it.
if h.palette_open && ev.Event_type != loop.MOUSE_MOVE {
return nil
}
switch ev.Event_type { switch ev.Event_type {
case loop.MOUSE_PRESS:
// Wheel notches arrive as presses carrying a wheel button. Moving the
// selection keeps the list scrolled to the row under it, without sending
// the event to the terminal that hosts the dock.
switch {
case ev.Buttons&loop.MOUSE_WHEEL_UP != 0:
h.move_selection(-wheel_scroll_lines)
case ev.Buttons&loop.MOUSE_WHEEL_DOWN != 0:
h.move_selection(wheel_scroll_lines)
}
case loop.MOUSE_CLICK: case loop.MOUSE_CLICK:
if ev.Buttons&loop.LEFT_MOUSE_BUTTON != 0 { switch {
case ev.Buttons&loop.LEFT_MOUSE_BUTTON != 0:
idx := h.row_to_entry(ev.Cell.Y)
if idx < 0 {
return nil
}
h.selected = idx
if h.clicks.is_double(time.Now(), idx) {
h.activate()
return nil
}
h.draw_screen()
case ev.Buttons&loop.RIGHT_MOUSE_BUTTON != 0:
// The context menu is the action palette that :: already opens, so
// every panel action is reachable from the pointer too.
if idx := h.row_to_entry(ev.Cell.Y); idx >= 0 { if idx := h.row_to_entry(ev.Cell.Y); idx >= 0 {
h.selected = idx h.selected = idx
h.draw_screen()
} }
h.open_palette()
} }
case loop.MOUSE_MOVE: case loop.MOUSE_MOVE:
h.lp.ClearPointerShapes() h.lp.ClearPointerShapes()
+126 -2
View File
@@ -8,6 +8,8 @@ import (
"path/filepath" "path/filepath"
"testing" "testing"
"time" "time"
"github.com/kovidgoyal/kitty/tools/tui/loop"
) )
func TestSortEntriesDirectoriesFirstThenByName(t *testing.T) { func TestSortEntriesDirectoriesFirstThenByName(t *testing.T) {
@@ -80,6 +82,66 @@ func TestReadDirReportsErrors(t *testing.T) {
} }
} }
func TestReadDirAcceptsAnEmptyDirectory(t *testing.T) {
entries, err := read_dir(t.TempDir(), false, "name")
if err != nil {
t.Fatal(err)
}
if len(entries) != 0 {
t.Fatalf("an empty directory must list nothing, got %#v", entries)
}
}
func TestReadDirReportsPermissionDenied(t *testing.T) {
dir := t.TempDir()
if err := os.Chmod(dir, 0o000); err != nil {
t.Skipf("cannot change permissions: %v", err)
}
// Make the directory readable again before TempDir cleans it up.
defer os.Chmod(dir, 0o700) //nolint:errcheck
if _, err := read_dir(dir, false, "name"); err == nil {
t.Skip("the current user can read a mode 000 directory, probably running as root")
}
}
func TestReadDirTreatsSymlinkedDirectoryAsDirectory(t *testing.T) {
dir := t.TempDir()
if err := os.Mkdir(filepath.Join(dir, "target"), 0o755); err != nil {
t.Fatal(err)
}
if err := os.Symlink("target", filepath.Join(dir, "link")); err != nil {
t.Skipf("cannot create symlinks: %v", err)
}
entries, err := read_dir(dir, false, "name")
if err != nil {
t.Fatal(err)
}
for _, e := range entries {
if e.Name == "link" {
if !e.IsDir {
t.Fatal("a symlink to a directory must be browsable, not opened as a file")
}
return
}
}
t.Fatalf("the symlink is missing from the listing: %#v", entries)
}
func TestReadDirHandlesNonUTF8Names(t *testing.T) {
dir := t.TempDir()
name := string([]byte{'b', 'a', 'd', 0xff, '.', 't', 'x', 't'})
if err := os.WriteFile(filepath.Join(dir, name), nil, 0o644); err != nil {
t.Skipf("the filesystem rejects non-UTF-8 names: %v", err)
}
entries, err := read_dir(dir, false, "name")
if err != nil {
t.Fatal(err)
}
if len(entries) != 1 || entries[0].Name != name {
t.Fatalf("the non-UTF-8 name must be listed unchanged, got %#v", entries)
}
}
func TestValidateEntryName(t *testing.T) { func TestValidateEntryName(t *testing.T) {
for _, name := range []string{"", ".", "..", "a/b", "a\x00b"} { for _, name := range []string{"", ".", "..", "a/b", "a\x00b"} {
if err := validate_entry_name(name); err == nil { if err := validate_entry_name(name); err == nil {
@@ -148,6 +210,22 @@ func TestCreateRenameAndDelete(t *testing.T) {
} }
} }
func TestResolveStartDirExpandsHome(t *testing.T) {
home := t.TempDir()
projects := filepath.Join(home, "projects")
if err := os.Mkdir(projects, 0o755); err != nil {
t.Fatal(err)
}
t.Setenv("HOME", home)
got, err := resolve_start_dir("~/projects")
if err != nil {
t.Fatal(err)
}
if got != projects {
t.Fatalf("resolve_start_dir(~/projects) = %q, wanted %q", got, projects)
}
}
func TestResolveStartDirAcceptsFiles(t *testing.T) { func TestResolveStartDirAcceptsFiles(t *testing.T) {
dir := t.TempDir() dir := t.TempDir()
file := filepath.Join(dir, "file.txt") file := filepath.Join(dir, "file.txt")
@@ -298,8 +376,13 @@ func TestFilterEntriesLargeDirectory(t *testing.T) {
if len(matches) == 0 { if len(matches) == 0 {
t.Fatal("expected matches in a large directory") t.Fatal("expected matches in a large directory")
} }
if elapsed > 100*time.Millisecond { // The bound is deliberately loose: this guards against the filter becoming
t.Fatalf("filtering 10000 entries took %s, the limit is 100ms", elapsed) // 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)
} }
} }
@@ -354,6 +437,47 @@ func TestEditArgsInWindow(t *testing.T) {
} }
} }
func TestRowToEntryAccountsForScroll(t *testing.T) {
h := &Handler{
screen_size: loop.ScreenSize{WidthCells: 40, HeightCells: 10},
entries: make([]Entry, 12),
scroll: 3,
}
// The list starts on row 2 and the status line takes the last row, so rows
// 2..8 display entries 3..9
cases := map[int]int{0: -1, 1: 3, 4: 6, 7: 9, 8: -1, 9: -1}
for cell_y, want := range cases {
if got := h.row_to_entry(cell_y); got != want {
t.Fatalf("cell Y %d: wanted entry %d, got %d", cell_y, want, got)
}
}
// A scroll past the end of the list maps to no entry rather than panicking
h.scroll = 20
if got := h.row_to_entry(1); got != -1 {
t.Fatalf("wanted no entry past the end of the list, got %d", got)
}
}
func TestClickTrackerDetectsDoubleClick(t *testing.T) {
start := time.Unix(1000, 0)
var c click_tracker
if c.is_double(start, 2) {
t.Fatal("a first click must not be a double click")
}
if !c.is_double(start.Add(200*time.Millisecond), 2) {
t.Fatal("a second click on the same row within the interval is a double click")
}
if c.is_double(start.Add(5*time.Second), 2) {
t.Fatal("a click after the interval must not be a double click")
}
if c.is_double(start.Add(5*time.Second+100*time.Millisecond), 7) {
t.Fatal("a click on another row must not be a double click")
}
if !c.is_double(start.Add(5*time.Second+200*time.Millisecond), 7) {
t.Fatal("the tracker must accept the row clicked last")
}
}
func TestTruncateToWidth(t *testing.T) { func TestTruncateToWidth(t *testing.T) {
if got := truncate_to_width("abcdef", 3); got != "ab\u2026" { if got := truncate_to_width("abcdef", 3); got != "ab\u2026" {
t.Fatalf("unexpected truncation %q", got) t.Fatalf("unexpected truncation %q", got)
+18
View File
@@ -66,6 +66,24 @@ func rune_to_index_map(alphabet string) *map[rune]int {
return &runeToIndexMap return &runeToIndexMap
} }
// next_selection moves pos by delta positions in a list of marks choices,
// wrapping around, as the arrow keys do in the list picker. A negative pos,
// meaning nothing is selected yet, selects the first choice when moving down
// and the last one when moving up, and a stale pos falls back to the first
// choice so that the arrow keys never stop working.
func next_selection(pos, marks, delta int) int {
if marks < 1 {
return -1
}
if pos < 0 || pos >= marks {
if delta < 0 {
return marks - 1
}
return 0
}
return ((pos+delta)%marks + marks) % marks
}
// decode_hint converts a hint to its corresponding index as it would appear in // decode_hint converts a hint to its corresponding index as it would appear in
// the breadth-first traversal of the prefix tree generated by the given // the breadth-first traversal of the prefix tree generated by the given
// alphabet. // alphabet.
+110 -24
View File
@@ -7,6 +7,7 @@ import (
"fmt" "fmt"
"io" "io"
"os" "os"
"sort"
"strconv" "strconv"
"strings" "strings"
"unicode" "unicode"
@@ -160,6 +161,10 @@ func main(_ *cli.Command, o *Options, args []string) (rc int, err error) {
} }
} }
chosen := []*Mark{} chosen := []*Mark{}
// The list navigation is only offered when the input is an ordered list of
// choices, see the --pick-from-list option.
pick_from_list := o.PickFromList
selected_mark := -1
lp, err := loop.New(loop.NoAlternateScreen) // no alternate screen reduces flicker on exit lp, err := loop.New(loop.NoAlternateScreen) // no alternate screen reduces flicker on exit
if err != nil { if err != nil {
return return
@@ -168,8 +173,9 @@ func main(_ *cli.Command, o *Options, args []string) (rc int, err error) {
faint := fctx.SprintFunc("dim") faint := fctx.SprintFunc("dim")
hint_style := fctx.SprintFunc(fmt.Sprintf("fg=%s bg=%s bold", o.HintsForegroundColor, o.HintsBackgroundColor)) hint_style := fctx.SprintFunc(fmt.Sprintf("fg=%s bg=%s bold", o.HintsForegroundColor, o.HintsBackgroundColor))
text_style := fctx.SprintFunc(fmt.Sprintf("fg=%s bg=%s bold", o.HintsTextColor, o.HintsTextBackgroundColor)) text_style := fctx.SprintFunc(fmt.Sprintf("fg=%s bg=%s bold", o.HintsTextColor, o.HintsTextBackgroundColor))
selected_style := fctx.SprintFunc("reverse")
highlight_mark := func(m *Mark, mark_text string) string { highlight_mark := func(m *Mark, mark_text string, selected bool) string {
hint := encode_hint(m.Index, alphabet) hint := encode_hint(m.Index, alphabet)
if current_input != "" && !strings.HasPrefix(hint, current_input) { if current_input != "" && !strings.HasPrefix(hint, current_input) {
return faint(mark_text) return faint(mark_text)
@@ -207,6 +213,9 @@ func main(_ *cli.Command, o *Options, args []string) (rc int, err error) {
mark_text = string(runes[hint_runes:]) mark_text = string(runes[hint_runes:])
} }
ans := hint_style(hint) + text_style(mark_text) ans := hint_style(hint) + text_style(mark_text)
if selected {
ans = selected_style(ans)
}
return fmt.Sprintf("\x1b]8;;mark:%d\a%s\x1b]8;;\a", m.Index, ans) return fmt.Sprintf("\x1b]8;;mark:%d\a%s\x1b]8;;\a", m.Index, ans)
} }
@@ -217,7 +226,7 @@ func main(_ *cli.Command, o *Options, args []string) (rc int, err error) {
if ignore_mark_indices.Has(mark.Index) { if ignore_mark_indices.Has(mark.Index) {
continue continue
} }
mtext := highlight_mark(mark, ans[mark.Start:mark.End]) 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 = ans[:mark.Start] + mtext + ans[mark.End:]
} }
ans = strings.ReplaceAll(ans, "\x00", "") ans = strings.ReplaceAll(ans, "\x00", "")
@@ -238,6 +247,75 @@ func main(_ *cli.Command, o *Options, args []string) (rc int, err error) {
current_text = "" current_text = ""
} }
// The marks in the order they were given, which is the order of the list
// the user sees rather than the order of the hints
ordered_indices := make([]int, 0, len(index_map))
for idx := range index_map {
ordered_indices = append(ordered_indices, idx)
}
sort.Ints(ordered_indices)
visible_marks := func() []*Mark {
ans := make([]*Mark, 0, len(ordered_indices))
for _, idx := range ordered_indices {
m := index_map[idx]
if m == nil || ignore_mark_indices.Has(m.Index) {
continue
}
if current_input != "" && !strings.HasPrefix(encode_hint(idx, alphabet), current_input) {
continue
}
ans = append(ans, m)
}
return ans
}
select_first := func() {
selected_mark = -1
if marks := visible_marks(); len(marks) > 0 {
selected_mark = marks[0].Index
}
}
choose_index := func(idx int) {
m := index_map[idx]
if m == nil {
current_input = ""
current_text = ""
draw_screen()
return
}
chosen = append(chosen, m)
ignore_mark_indices.Add(m.Index)
if o.Multiple {
reset()
select_first()
draw_screen()
} else {
lp.Quit(0)
}
}
select_by := func(delta int) {
marks := visible_marks()
if len(marks) == 0 {
return
}
pos := -1
for i, m := range marks {
if m.Index == selected_mark {
pos = i
break
}
}
if pos < 0 {
pos = 0
}
pos = next_selection(pos, len(marks), delta)
selected_mark = marks[pos].Index
current_text = ""
draw_screen()
}
if pick_from_list {
select_first()
}
lp.OnInitialize = func() (string, error) { lp.OnInitialize = func() (string, error) {
lp.SetCursorVisible(false) lp.SetCursorVisible(false)
lp.SetWindowTitle(window_title) lp.SetWindowTitle(window_title)
@@ -295,13 +373,15 @@ func main(_ *cli.Command, o *Options, args []string) (rc int, err error) {
} }
if len(matches) == 1 { if len(matches) == 1 {
chosen = append(chosen, matches[0]) chosen = append(chosen, matches[0])
if o.Multiple { ignore_mark_indices.Add(matches[0].Index)
ignore_mark_indices.Add(matches[0].Index) if !o.Multiple {
reset()
} else {
lp.Quit(0) lp.Quit(0)
return nil return nil
} }
reset()
}
if pick_from_list {
select_first()
} }
current_text = "" current_text = ""
draw_screen() draw_screen()
@@ -310,7 +390,14 @@ func main(_ *cli.Command, o *Options, args []string) (rc int, err error) {
} }
lp.OnKeyEvent = func(ev *loop.KeyEvent) error { lp.OnKeyEvent = func(ev *loop.KeyEvent) error {
if 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 ev.Handled = true
r := []rune(current_input) r := []rune(current_input)
if len(r) > 0 { 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_input = string(r)
current_text = "" current_text = ""
} }
if pick_from_list {
select_first()
}
draw_screen() draw_screen()
} else if ev.MatchesPressOrRepeat("enter") || ev.MatchesPressOrRepeat("space") { } else if ev.MatchesPressOrRepeat("enter") {
ev.Handled = true ev.Handled = true
if current_input != "" { if pick_from_list {
char_to_index := rune_to_index_map(alphabet) if selected_mark > -1 {
idx := decode_hint(current_input, char_to_index) choose_index(selected_mark)
if m := index_map[idx]; m != nil { } else if marks := visible_marks(); len(marks) > 0 {
chosen = append(chosen, m) choose_index(marks[0].Index)
ignore_mark_indices.Add(idx)
if o.Multiple {
reset()
draw_screen()
} else {
lp.Quit(0)
}
} else {
current_input = ""
current_text = ""
draw_screen()
} }
} else if current_input != "" {
choose_index(decode_hint(current_input, rune_to_index_map(alphabet)))
}
} else if ev.MatchesPressOrRepeat("space") {
ev.Handled = true
if !pick_from_list && current_input != "" {
choose_index(decode_hint(current_input, rune_to_index_map(alphabet)))
} }
} else if ev.MatchesPressOrRepeat("esc") { } else if ev.MatchesPressOrRepeat("esc") {
if o.Multiple { if o.Multiple {
+8
View File
@@ -271,6 +271,14 @@ elsewhere. See {hints_url} for details.
--window-title --window-title
The title for the hints window, default title is based on the type of text being The title for the hints window, default title is based on the type of text being
hinted. hinted.
--pick-from-list
type=bool-set
The input is an ordered list of choices rather than text to search, as used by the
clipboard history picker. The first choice is selected and the arrow keys move the
selection, so a choice can be picked with :kbd:`Enter` instead of typing the
letters of its hint.
""".format( """.format(
default_regex=DEFAULT_REGEX, default_regex=DEFAULT_REGEX,
line='{{line}}', line='{{line}}',
+33
View File
@@ -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)
}
}
}
+28 -5
View File
@@ -3187,11 +3187,24 @@ class Boss:
q = ' '.join(text.split()) q = ' '.join(text.split())
return q if len(q) <= 120 else q[:117] + '…' return q if len(q) <= 120 else q[:117] + '…'
def _choose_from_clipboard_history(self, entries: tuple[str, ...]) -> None: 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: if not entries:
self.ring_bell_if_allowed() self.ring_bell_if_allowed()
return return
previews = [(text, self._clipboard_history_preview(text) or _('(blank)')) for text in entries] 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 # 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. # working in to paste into once it closes. The window can be gone by then.
target = self.window_for_dispatch or self.active_window target = self.window_for_dispatch or self.active_window
@@ -3202,11 +3215,18 @@ class Boss:
if w is not None: if w is not None:
w.paste_with_actions(text) w.paste_with_actions(text)
self.choose_entry(_('Clipboard history'), previews, chosen) 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`.') @ac('cp', 'Paste an entry from the clipboard history. See :ref:`clipboard_history`.')
def paste_from_clipboard_history(self) -> None: def paste_from_clipboard_history(self) -> None:
self._choose_from_clipboard_history(self.clipboard_history.entries()) 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`.') @ac('cp', 'Search the clipboard history and paste the selected entry. See :ref:`clipboard_history`.')
def search_clipboard_history(self) -> None: def search_clipboard_history(self) -> None:
@@ -3215,7 +3235,7 @@ class Boss:
return return
def query_entered(query: str) -> None: def query_entered(query: str) -> None:
self._choose_from_clipboard_history(self.clipboard_history.search(query)) self._choose_from_clipboard_history(self.clipboard_history.search_with_times(query))
self.get_line( self.get_line(
_('Search the clipboard history. Leave empty to list everything.'), _('Search the clipboard history. Leave empty to list everything.'),
@@ -3979,6 +3999,7 @@ class Boss:
callback: Callable[[_T | str | None], None], callback: Callable[[_T | str | None], None],
subtitle: str = '', subtitle: str = '',
hints_args: tuple[str, ...] | None = None, hints_args: tuple[str, ...] | None = None,
footer: str = '',
) -> Window | None: ) -> Window | None:
lines = [title, subtitle, ' '] if subtitle else [title, ' '] lines = [title, subtitle, ' '] if subtitle else [title, ' ']
idx_map: list[_T | str | None] = [] idx_map: list[_T | str | None] = []
@@ -3991,6 +4012,8 @@ class Boss:
lines.append(text) lines.append(text)
else: else:
lines.append(fmt.format(len(idx_map), text)) lines.append(fmt.format(len(idx_map), text))
if footer:
lines.append(f' {footer}')
def done(data: dict[str, Any], target_window_id: int, self: Boss) -> None: def done(data: dict[str, Any], target_window_id: int, self: Boss) -> None:
nonlocal ans nonlocal ans
+24 -13
View File
@@ -7,7 +7,7 @@
# help within one kitty instance, not to outlive it. Entries marked private are never recorded. # help within one kitty instance, not to outlive it. Entries marked private are never recorded.
from collections import deque from collections import deque
from contextlib import suppress from time import time
from typing import Iterator from typing import Iterator
DEFAULT_MAX_ENTRIES = 50 DEFAULT_MAX_ENTRIES = 50
@@ -76,7 +76,7 @@ class ClipboardHistory:
self.max_entries = max(1, max_entries) self.max_entries = max(1, max_entries)
self.max_entry_chars = max(1, max_entry_chars) self.max_entry_chars = max(1, max_entry_chars)
self.max_total_chars = max(1, max_total_chars) self.max_total_chars = max(1, max_total_chars)
self._entries: deque[str] = deque() self._entries: deque[tuple[str, float]] = deque()
self._total_chars = 0 self._total_chars = 0
def __len__(self) -> int: def __len__(self) -> int:
@@ -86,43 +86,54 @@ class ClipboardHistory:
return bool(self._entries) return bool(self._entries)
def __iter__(self) -> Iterator[str]: def __iter__(self) -> Iterator[str]:
return reversed(self._entries) return iter(self.entries())
def __getitem__(self, idx: int) -> str: def __getitem__(self, idx: int) -> str:
return self.entries()[idx] return self.entries()[idx]
def entries(self) -> tuple[str, ...]: def entries(self) -> tuple[str, ...]:
"""All entries, most recently copied first.""" """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)) return tuple(reversed(self._entries))
def clear(self) -> None: def clear(self) -> None:
self._entries.clear() self._entries.clear()
self._total_chars = 0 self._total_chars = 0
def add(self, text: str, private: bool = False) -> bool: def add(self, text: str, private: bool = False, timestamp: float | None = None) -> bool:
"""Record text, returning False when it is deliberately not recorded.""" """Record text, returning False when it is deliberately not recorded."""
if private or not text or not text.strip(): if private or not text or not text.strip():
return False return False
if len(text) > self.max_entry_chars: if len(text) > self.max_entry_chars:
return False return False
# A repeated copy moves the entry to the top instead of duplicating it # A repeated copy moves the entry to the top instead of duplicating it
with suppress(ValueError): for idx, (old_text, _) in enumerate(self._entries):
self._entries.remove(text) if old_text == text:
self._total_chars -= len(text) del self._entries[idx]
self._entries.append(text) self._total_chars -= len(old_text)
break
self._entries.append((text, time() if timestamp is None else timestamp))
self._total_chars += len(text) self._total_chars += len(text)
while self._entries and (len(self._entries) > self.max_entries or self._total_chars > self.max_total_chars): 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()) self._total_chars -= len(self._entries.popleft()[0])
return True return True
def search(self, query: str) -> tuple[str, ...]: def search(self, query: str) -> tuple[str, ...]:
"""Entries matching query, best match first, newest first among equal scores.""" """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(): if not query.strip():
return self.entries() return entries
scored = [] scored = []
for idx, text in enumerate(self.entries()): for idx, (text, when) in enumerate(entries):
score = match_score(query, text) score = match_score(query, text)
if score > -1: if score > -1:
scored.append((score, idx, text)) scored.append((score, idx, text, when))
scored.sort(key=lambda x: (x[0], x[1])) scored.sort(key=lambda x: (x[0], x[1]))
return tuple(text for _, _, text in scored) return tuple((text, when) for _, _, text, when in scored)
+2 -2
View File
@@ -424,10 +424,10 @@ handle_fast_commandline(CLISpec *cli_spec, const char *instance_group_prefix) {
if (get_bool_cli_val(cli_spec, "version")) { if (get_bool_cli_val(cli_spec, "version")) {
if (isatty(STDOUT_FILENO)) { if (isatty(STDOUT_FILENO)) {
printf("\x1b[3mkitty\x1b[23m \x1b[32m%s\x1b[39m created by \x1b[1;34mKovid Goyal\x1b[22;39m\n", KITTY_VERSION); printf("\x1b[3mkitty\x1b[23m \x1b[32m%s\x1b[39m created by \x1b[1;34mKovid Goyal\x1b[22;39m\n", KITTY_VERSION);
printf("\x1b[3mfws-kitty\x1b[23m \x1b[32m0.1.7\x1b[39m by \x1b[1;34mBlackAngelTV\x1b[22;39m\n"); printf("\x1b[3mfws-kitty\x1b[23m \x1b[32m0.1.17\x1b[39m by \x1b[1;34mBlackAngelTV\x1b[22;39m\n");
} else { } else {
printf("kitty %s created by Kovid Goyal\n", KITTY_VERSION); printf("kitty %s created by Kovid Goyal\n", KITTY_VERSION);
printf("fws-kitty 0.1.7 by BlackAngelTV\n"); printf("fws-kitty 0.1.17 by BlackAngelTV\n");
} }
exit(0); exit(0);
} }
+19 -1
View File
@@ -2,7 +2,7 @@
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net> # License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
import re import re
from collections.abc import Callable, Generator, Iterable, Sequence from collections.abc import Callable, Generator, Iterable, Mapping, Sequence
from re import Pattern from re import Pattern
from typing import Union from typing import Union
@@ -29,6 +29,24 @@ def marker_from_regex(expression: Union[str, 'Pattern[str]'], color: int, flags:
return marker return marker
def marker_from_spans(spans: Mapping[str, Sequence[tuple[int, int, int]]]) -> MarkerFunc:
"""A marker built from pre-computed spans, keyed by the text of their line.
Each span is (start, end, color), where color is a mark number. Marker
functions receive one line at a time without its number, hence the lookup
by text.
"""
def marker(text: str, left_address: int, right_address: int, color_address: int) -> Generator[None, None, None]:
for start, end, color in spans.get(text, ()):
set_uint_at_address(left_address, start)
set_uint_at_address(right_address, end - 1)
set_uint_at_address(color_address, max(1, min(color, 3)))
yield
return marker
def marker_from_multiple_regex(regexes: Iterable[tuple[int, str]], flags: int = re.UNICODE) -> MarkerFunc: def marker_from_multiple_regex(regexes: Iterable[tuple[int, str]], flags: int = re.UNICODE) -> MarkerFunc:
expr = '' expr = ''
color_map = {} color_map = {}
+68
View File
@@ -2183,6 +2183,73 @@ update_mock_pointer(PyObject *self UNUSED, PyObject *args) {
return Py_BuildValue("(iO)", result, updated ? Py_True : Py_False); return Py_BuildValue("(iO)", result, updated ? Py_True : Py_False);
} }
/* Hit test a point against two windows placed side by side in a mock tab, and
* return 1 or 2 for the window mouse_region() picks, or 0 when none is hit.
* A docked window must receive the clicks in its own area, whatever the edge it
* is docked at, so the edges are given here rather than assumed to be left. */
static PyObject *
mock_window_under_mouse(PyObject *self UNUSED, PyObject *args) {
PyObject *capsule;
int g[2][4];
int mouse_x, mouse_y;
if (!PyArg_ParseTuple(
args,
"O!iiiiiiiiii",
&PyCapsule_Type,
&capsule,
&g[0][0],
&g[0][1],
&g[0][2],
&g[0][3],
&g[1][0],
&g[1][1],
&g[1][2],
&g[1][3],
&mouse_x,
&mouse_y))
return NULL;
Window *w = PyCapsule_GetPointer(capsule, "Window");
if (!w) return NULL;
Screen *screen = w->render_data.screen;
if (!screen) return NULL;
OSWindow *saved_os_window = global_state.callback_os_window;
const id_type saved_hover = global_state.mouse_hover_in_window;
Window windows[2] = {*w, *w};
for (unsigned int i = 0; i < 2; i++) {
Window *win = windows + i;
win->id = w->id + i;
win->visible = true;
win->render_data.screen = screen;
win->render_data.geometry.left = (unsigned int)MAX(0, g[i][0]);
win->render_data.geometry.top = (unsigned int)MAX(0, g[i][1]);
win->render_data.geometry.right = (unsigned int)MAX(0, g[i][2]);
win->render_data.geometry.bottom = (unsigned int)MAX(0, g[i][3]);
zero_at_ptr(&win->padding);
zero_at_ptr(&win->size_mismatch_padding);
}
Tab tab = {.windows = windows, .num_windows = 2};
struct {
FONTS_DATA_HEAD
} fonts = {.logical_dpi_x = 72, .logical_dpi_y = 72, .fcm = {.cell_width = 10, .cell_height = 20}};
OSWindow osw = {
.tabs = &tab,
.num_tabs = 1,
.has_too_few_tabs = true,
.fonts_data = (FONTS_DATA_HANDLE)&fonts,
.viewport_width = 1400,
.viewport_height = 600,
.mouse_x = (double)mouse_x,
.mouse_y = (double)mouse_y};
global_state.callback_os_window = &osw;
global_state.mouse_hover_in_window = 0;
MouseRegion region = mouse_region(false, false);
unsigned long ans = region.window == windows ? 1 : region.window == windows + 1 ? 2 : 0;
global_state.callback_os_window = saved_os_window;
global_state.mouse_hover_in_window = saved_hover;
if (PyErr_Occurred()) return NULL;
return PyLong_FromUnsignedLong(ans);
}
static PyObject * static PyObject *
test_scale_scroll(PyObject *self UNUSED, PyObject *args) { test_scale_scroll(PyObject *self UNUSED, PyObject *args) {
PyObject *values; PyObject *values;
@@ -2258,6 +2325,7 @@ static PyMethodDef module_methods[] = {
METHODB(test_mapped_scroll_steps, METH_VARARGS), METHODB(test_mapped_scroll_steps, METH_VARARGS),
METHODB(send_mock_mouse_event_to_window, METH_VARARGS), METHODB(send_mock_mouse_event_to_window, METH_VARARGS),
METHODB(update_mock_pointer, METH_VARARGS), METHODB(update_mock_pointer, METH_VARARGS),
METHODB(mock_window_under_mouse, METH_VARARGS),
METHODB(send_mock_scroll_event_to_window, METH_VARARGS), METHODB(send_mock_scroll_event_to_window, METH_VARARGS),
METHODB(mock_mouse_selection, METH_VARARGS), METHODB(mock_mouse_selection, METH_VARARGS),
{NULL, NULL, 0, NULL} /* Sentinel */ {NULL, NULL, 0, NULL} /* Sentinel */
+7 -4
View File
@@ -4159,13 +4159,14 @@ map('Search the scrollback within a pager', 'search_scrollback --allow-fallback=
map( map(
'Search and highlight the scrollback in place', 'Search and highlight the scrollback in place',
'search_scrollback_prompt kitty_mod+shift+f search_scrollback_prompt', 'search_scrollback_prompt kitty_mod+alt+s search_scrollback_prompt',
long_text=""" long_text="""
Search the scrollback without opening a pager. Every match is highlighted in 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. 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 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 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 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 The :ac:`scrollback_search_next`, :ac:`scrollback_search_prev` and
:ac:`clear_scrollback_search` actions can be mapped to other keys. :ac:`clear_scrollback_search` actions can be mapped to other keys.
@@ -4719,11 +4720,13 @@ map('Command palette', 'command_palette kitty_mod+f3 command_palette')
map( map(
'Keyboard shortcuts', 'Keyboard shortcuts',
'keyboard_shortcuts kitty_mod+h launch --type=window-dock --dock-edge=left --dock-size=60 kitty +kitten help', 'keyboard_shortcuts kitty_mod+alt+h launch --type=window-dock --dock-edge=left --dock-size=60 kitty +kitten help',
long_text=""" long_text="""
Open the searchable keyboard shortcuts panel in a dock at the left edge of the 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`. current window. It can also be launched manually with :code:`kitty +kitten help`.
The default binding is :kbd:`kitty_mod+h` (:kbd:`Ctrl+Shift+H` by default). 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`.
""", """,
) )
+2 -2
View File
@@ -937,7 +937,7 @@ defaults.map = [
# search_scrollback # search_scrollback
KeyDefinition(trigger=SingleKey(mods=256, key=47), definition='search_scrollback'), KeyDefinition(trigger=SingleKey(mods=256, key=47), definition='search_scrollback'),
# search_scrollback_prompt # search_scrollback_prompt
KeyDefinition(trigger=SingleKey(mods=257, key=102), definition='search_scrollback_prompt'), KeyDefinition(trigger=SingleKey(mods=258, key=115), definition='search_scrollback_prompt'),
# new_window # new_window
KeyDefinition(trigger=SingleKey(mods=256, key=57345), definition='new_window'), KeyDefinition(trigger=SingleKey(mods=256, key=57345), definition='new_window'),
# new_os_window # new_os_window
@@ -1041,7 +1041,7 @@ defaults.map = [
# file_manager # file_manager
KeyDefinition(trigger=SingleKey(mods=5, key=101), definition='launch --type=window-dock --dock-edge=left --dock-size=60 kitten file-manager'), KeyDefinition(trigger=SingleKey(mods=5, key=101), definition='launch --type=window-dock --dock-edge=left --dock-size=60 kitten file-manager'),
# keyboard_shortcuts # keyboard_shortcuts
KeyDefinition(trigger=SingleKey(mods=5, key=104), definition='launch --type=window-dock --dock-edge=left --dock-size=60 kitty +kitten help'), KeyDefinition(trigger=SingleKey(mods=258, key=104), definition='launch --type=window-dock --dock-edge=left --dock-size=60 kitty +kitten help'),
# toggle_fullscreen # toggle_fullscreen
KeyDefinition(trigger=SingleKey(mods=256, key=57374), definition='toggle_fullscreen'), KeyDefinition(trigger=SingleKey(mods=256, key=57374), definition='toggle_fullscreen'),
# toggle_maximized # toggle_maximized
+32 -1
View File
@@ -6,17 +6,24 @@
The query parser and the matcher live here, away from the screen code, so that 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 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`` modifiers, in any order: ``\\c`` makes matching case sensitive and ``\\r``
treats the query as a regular expression. 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 from __future__ import annotations
import re import re
from collections.abc import Sequence
from dataclasses import dataclass, field from dataclasses import dataclass, field
CASE_SENSITIVE_MODIFIER = 'c' CASE_SENSITIVE_MODIFIER = 'c'
REGEX_MODIFIER = 'r' 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): class InvalidQuery(ValueError):
pass pass
@@ -51,12 +58,36 @@ class ScrollbackSearch:
def __len__(self) -> int: def __len__(self) -> int:
return len(self.matches) 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: def parse_query(raw: str) -> Query:
text = (raw or '').strip() text = (raw or '').strip()
case_sensitive = is_regex = False case_sensitive = is_regex = False
while len(text) > 1 and text[0] == '\\': while len(text) > 1 and text[0] == '\\':
modifier = text[1].lower() 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: if modifier == CASE_SENSITIVE_MODIFIER:
case_sensitive = True case_sensitive = True
elif modifier == REGEX_MODIFIER: elif modifier == REGEX_MODIFIER:
+23 -6
View File
@@ -827,6 +827,7 @@ class Window:
self.actions_on_removal: list[Callable[['Window'], None]] = [] self.actions_on_removal: list[Callable[['Window'], None]] = []
self.current_marker_spec: tuple[str, str | tuple[tuple[int, str], ...]] | None = None self.current_marker_spec: tuple[str, str | tuple[tuple[int, str], ...]] | None = None
self.scrollback_search: ScrollbackSearch | None = None self.scrollback_search: ScrollbackSearch | None = None
self.scrollback_search_spans: dict[str, tuple[tuple[int, int, int], ...]] = {}
self.scrollback_search_mode: str = '' self.scrollback_search_mode: str = ''
self.scrollback_search_saved_marker: tuple[str, str | tuple[tuple[int, str], ...]] | None = None self.scrollback_search_saved_marker: tuple[str, str | tuple[tuple[int, str], ...]] | None = None
self.scrollback_search_saved_title: str | None = None self.scrollback_search_saved_title: str | None = None
@@ -2676,8 +2677,10 @@ class Window:
'sc', 'sc',
""" """
Search the scrollback in place, highlighting every match. Prefix the query with \\c for a case 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. Matches are navigated with n and N and sensitive search and with \\r for a regular expression. To search for those two strings literally,
the search ends with Escape. The [current/total] counter is shown in the window title. 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: def search_scrollback_prompt(self) -> bool | None:
@@ -2691,7 +2694,10 @@ class Window:
self.clear_scrollback_search() self.clear_scrollback_search()
get_boss().get_line( get_boss().get_line(
_('Search the scrollback. Prefix the query with \\c for a case sensitive search and \\r for a regular expression.'), _(
'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, done,
window=self, window=self,
prompt=_('search> '), prompt=_('search> '),
@@ -2724,12 +2730,12 @@ class Window:
ring_bell(self.os_window_id) ring_bell(self.os_window_id)
return return
self.clear_scrollback_search() self.clear_scrollback_search()
from .marks import marker_from_regex
self.scrollback_search = ScrollbackSearch(query, pattern, matches, total_lines=len(lines)) 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_marker = self.current_marker_spec
self.scrollback_search_saved_title = self.override_title self.scrollback_search_saved_title = self.override_title
self.screen.set_marker(marker_from_regex(pattern, 1))
self._push_scrollback_search_mode() self._push_scrollback_search_mode()
self._goto_scrollback_match(0) self._goto_scrollback_match(0)
@@ -2738,6 +2744,7 @@ class Window:
if self.scrollback_search is None: if self.scrollback_search is None:
return return
self.scrollback_search = None self.scrollback_search = None
self.scrollback_search_spans = {}
self.screen.set_marker() self.screen.set_marker()
self.current_marker_spec = None self.current_marker_spec = None
saved = self.scrollback_search_saved_marker saved = self.scrollback_search_saved_marker
@@ -2781,8 +2788,18 @@ class Window:
search.index = index % len(search.matches) search.index = index % len(search.matches)
match = search.matches[search.index] match = search.matches[search.index]
self.set_title(f'[{search.index + 1}/{len(search.matches)}] {search.query.text}') 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)) 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: def _push_scrollback_search_mode(self) -> None:
from .fast_data_types import GLFW_FKEY_ESCAPE, GLFW_MOD_SHIFT from .fast_data_types import GLFW_FKEY_ESCAPE, GLFW_MOD_SHIFT
from .options.utils import KeyboardMode, KeyDefinition, SingleKey from .options.utils import KeyboardMode, KeyDefinition, SingleKey
+13
View File
@@ -78,6 +78,19 @@ class TestClipboardHistory(BaseTest):
self.ae(h.search('mkb'), ('make build',)) self.ae(h.search('mkb'), ('make build',))
self.ae(h.search('zzz'), ()) 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: def test_substring_matches_rank_before_subsequences(self) -> None:
h = ClipboardHistory() h = ClipboardHistory()
h.add('xkcd') h.add('xkcd')
+13
View File
@@ -126,6 +126,16 @@ class TestDocks(BaseTest):
content, placements = carve_docks(Region((0, 0, -1, -1, 0, 0)), groups, CELL_WIDTH, CELL_HEIGHT) content, placements = carve_docks(Region((0, 0, -1, -1, 0, 0)), groups, CELL_WIDTH, CELL_HEIGHT)
self.ae([r.height for g, r in placements], [0, 0]) self.ae([r.height for g, r in placements], [0, 0])
# A dock at the right is placed against the right edge of what remains,
# the same way a dock at the left is placed against the left edge
groups = []
left, right = dock('left', '10%'), dock('right', '5%')
content, placements = carve_docks(VIEWPORT, groups, CELL_WIDTH, CELL_HEIGHT)
regions = {g.id: rect(r) for g, r in placements}
self.ae(regions[left.id], (0, 0, 100, 600))
self.ae(regions[right.id], (950, 0, 1000, 600))
self.ae(rect(content), (100, 0, 950, 600))
def test_tab_docks(self): def test_tab_docks(self):
q = make_layout(Tall) q = make_layout(Tall)
windows = make_windows(q, 2) windows = make_windows(q, 2)
@@ -183,6 +193,9 @@ class TestDocks(BaseTest):
self.assertTrue(rect(r)[0] >= allocated.left and rect(r)[2] <= allocated.left + allocated.width) self.assertTrue(rect(r)[0] >= allocated.left and rect(r)[2] <= allocated.left + allocated.width)
self.ae(rect(dock_regions[0])[1], allocated.top + allocated.height - 2 * CELL_HEIGHT - 2 * DECORATION) self.ae(rect(dock_regions[0])[1], allocated.top + allocated.height - 2 * CELL_HEIGHT - 2 * DECORATION)
self.ae(dock_regions[1].width, allocated.width // 4) self.ae(dock_regions[1].width, allocated.width // 4)
# The dock at the right sits past the content, at the right of the area
self.assertGreaterEqual(rect(dock_regions[1])[0], rect(content)[2])
self.assertLessEqual(rect(dock_regions[1])[2], allocated.left + allocated.width)
self.check_no_overlaps(windows) self.check_no_overlaps(windows)
# The decorations chosen by the layout for the owner are preserved # The decorations chosen by the layout for the owner are preserved
self.ae(main.geometry.spaces.left - main.geometry.compensatory.left, DECORATION) self.ae(main.geometry.spaces.left - main.geometry.compensatory.left, DECORATION)
+79
View File
@@ -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()
+28
View File
@@ -834,3 +834,31 @@ class TestMouse(BaseTest):
ac([], 4) ac([], 4)
self.assertTrue(s.callbacks.wtcbuf, 'the wheel event was not reported to the program') self.assertTrue(s.callbacks.wtcbuf, 'the wheel event was not reported to the program')
parse_bytes(s, b'\x1b[?1000l') parse_bytes(s, b'\x1b[?1000l')
def test_docked_window_receives_clicks_at_any_edge(self):
from kitty.fast_data_types import mock_window_under_mouse
s = self.create_screen(cols=140, lines=30)
w = create_mock_window(s)
terminal, right_dock = (0, 0, 1000, 600), (1000, 0, 1400, 600)
left_dock, offset_terminal = (0, 0, 400, 600), (400, 0, 1400, 600)
def under(first, second, x, y):
return mock_window_under_mouse(w, *first, *second, x, y)
# A dock at the right receives the clicks in its own area and the
# terminal receives the clicks in the area left over
self.ae(under(terminal, right_dock, 500, 300), 1)
self.ae(under(terminal, right_dock, 999, 300), 1)
self.ae(under(terminal, right_dock, 1000, 300), 2)
self.ae(under(terminal, right_dock, 1200, 300), 2)
# Swapping the two areas over must give the same answer for a dock at
# the left, so the hit test does not depend on the edge
self.ae(under(left_dock, offset_terminal, 500, 300), 2)
self.ae(under(left_dock, offset_terminal, 100, 300), 1)
self.ae(under(left_dock, offset_terminal, 399, 300), 1)
# The first window wins when two areas overlap, as with an overlay
self.ae(under(terminal, (500, 0, 1400, 600), 700, 300), 1)
# A window with an empty area is never hit, even inside the other one
self.ae(under(terminal, (0, 0, 0, 0), 1200, 300), 0)
self.ae(under((0, 0, 0, 0), right_dock, 1200, 300), 2)
+25
View File
@@ -29,6 +29,31 @@ class TestConfParsing(BaseTest):
def test_conf_parsing(self): def test_conf_parsing(self):
conf_parsing(self) conf_parsing(self)
def test_default_shortcuts_have_no_duplicate_trigger(self):
from kitty.config import load_config
opts = load_config(overrides=())
keymap = opts.keyboard_modes[''].keymap
# The file manager deliberately takes kitty_mod+e over from open_url, a
# decision documented in the changelog. Every other collision means the
# last definition wins silently and one of the two actions is unreachable.
accepted = {frozenset(('launch', 'open_url_with_hints'))}
for key, defns in keymap.items():
actions = {d.definition.split()[0] for d in defns}
if len(actions) > 1 and frozenset(actions) not in accepted:
self.fail(f'{key!r} is claimed by several actions: {sorted(actions)}')
def test_default_search_shortcut(self):
from kitty.config import load_config
opts = load_config(overrides=())
keymap = opts.keyboard_modes[''].keymap
keys = [key for key, defns in keymap.items() if any(d.definition.split()[0] == 'search_scrollback_prompt' for d in defns)]
self.ae(len(keys), 1, 'the in-place search must have exactly one default shortcut')
# A shared trigger means the last definition wins silently and the search
# never opens, which is what happened with move_window_forward.
self.ae([d.definition.split()[0] for d in keymap[keys[0]]], ['search_scrollback_prompt'])
def test_launcher(self): def test_launcher(self):
launcher(self) launcher(self)
+44
View File
@@ -5,8 +5,11 @@ import re
import time import time
from kitty.scrollback_search import ( from kitty.scrollback_search import (
CURRENT_MATCH_COLOR,
MATCH_COLOR,
InvalidQuery, InvalidQuery,
Match, Match,
ScrollbackSearch,
compile_query, compile_query,
find_matches, find_matches,
parse_query, parse_query,
@@ -46,6 +49,25 @@ class TestScrollbackSearch(BaseTest):
with self.assertRaises(InvalidQuery): with self.assertRaises(InvalidQuery):
compile_query(parse_query('\\r (')) 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): def test_find_matches_plain(self):
lines = ['needle at start', 'Needle again', 'nothing', 'a needle here'] lines = ['needle at start', 'Needle again', 'nothing', 'a needle here']
matches = find_matches(lines, parse_query('needle')) matches = find_matches(lines, parse_query('needle'))
@@ -64,6 +86,28 @@ class TestScrollbackSearch(BaseTest):
# Empty matches are skipped and do not loop forever # Empty matches are skipped and do not loop forever
self.ae(find_matches(['abc'], parse_query('\\r x*')), []) 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): def test_scroll_offset(self):
self.ae(scroll_offset_for(Match(0, 0, 1), 100, 10), 90) 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(50, 0, 1), 100, 10), 43)
+6 -1
View File
@@ -13,7 +13,7 @@
pkgname=fws-kitty pkgname=fws-kitty
# Fork version from the version file: it names the release and the package. # Fork version from the version file: it names the release and the package.
# The upstream kitty release built inside is tracked by _kittyver below. # The upstream kitty release built inside is tracked by _kittyver below.
pkgver=0.1.7 pkgver=0.1.17
pkgrel=1 pkgrel=1
pkgdesc='Fast, feature-rich, GPU based terminal (FWS fork with the file-manager kitten)' pkgdesc='Fast, feature-rich, GPU based terminal (FWS fork with the file-manager kitten)'
arch=('x86_64' 'aarch64') arch=('x86_64' 'aarch64')
@@ -52,6 +52,11 @@ optdepends=(
provides=('kitty') provides=('kitty')
conflicts=('kitty') conflicts=('kitty')
# The release publishes only the main package, so the separate debug package is
# built and thrown away. Skipping it also avoids makepkg running gdb-add-index
# over binaries that were already stripped, which only prints errors.
options=('!debug')
source=( source=(
"$pkgname::git+$_repo#$_source_ref" "$pkgname::git+$_repo#$_source_ref"
"nerdfonts-symbols.tar.xz::https://github.com/ryanoasis/nerd-fonts/releases/download/v3.5.1/NerdFontsSymbolsOnly.tar.xz" "nerdfonts-symbols.tar.xz::https://github.com/ryanoasis/nerd-fonts/releases/download/v3.5.1/NerdFontsSymbolsOnly.tar.xz"
+13 -1
View File
@@ -87,10 +87,22 @@ Le workflow a besoin de deux secrets du dépôt :
Sans `REPO_TOKEN`, la release est créée mais le dépôt pacman n'est pas mis à 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 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 fork, incrémentez `pkgrel` ici et lancez le workflow manuellement ; le paquet
`0.1.7-2` remplace le `0.1.7-1` dans la base `fws.db` reconstruite côté `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 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`. 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 `pkgver` est la version du fork FWS (fichier `version` à la racine), pas celle
de kitty : la version amont embarquée est dans `_kittyver`. de kitty : la version amont embarquée est dans `_kittyver`.
`packaging/check-version.sh` vérifie avant le build que `version` et `pkgver` `packaging/check-version.sh` vérifie avant le build que `version` et `pkgver`
+1 -1
View File
@@ -31,7 +31,7 @@ func ShowError(err error) {
func (self *Command) version_string(formatter *markup.Context) string { func (self *Command) version_string(formatter *markup.Context) string {
return fmt.Sprintln(formatter.Italic(self.CommandStringForUsage()), formatter.Opt(kitty.VersionString+kitty.VersionSuffix), "created by", formatter.Title("Kovid Goyal")) + return fmt.Sprintln(formatter.Italic(self.CommandStringForUsage()), formatter.Opt(kitty.VersionString+kitty.VersionSuffix), "created by", formatter.Title("Kovid Goyal")) +
fmt.Sprintln(formatter.Italic("fws-kitty"), formatter.Opt("0.1.7"), "by", formatter.Title("BlackAngelTV")) fmt.Sprintln(formatter.Italic("fws-kitty"), formatter.Opt("0.1.17"), "by", formatter.Title("BlackAngelTV"))
} }
func (self *Command) ShowVersion() { func (self *Command) ShowVersion() {
+1 -1
View File
@@ -1 +1 @@
0.1.7 0.1.17