Compare commits
23
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d83fbc71e3 | ||
|
|
cbee630d4c
|
||
|
|
4df542f590
|
||
|
|
b406be9394 | ||
|
|
4ca4a516ae
|
||
|
|
f616651c49
|
||
|
|
1bd822b9e5
|
||
|
|
ce9f7ab974
|
||
|
|
603ef78a6e
|
||
|
|
f2f026c748
|
||
|
|
ec42571be5
|
||
|
|
dea1771fe5
|
||
|
|
0cce80a6c5
|
||
|
|
70befe3802
|
||
|
|
a3d0fd38b7
|
||
|
|
25840c6ce1
|
||
|
|
af032e3d87
|
||
|
|
533cc3873d
|
||
|
|
bd22a8c5f3
|
||
|
|
576189533c
|
||
|
|
5f232ff99c
|
||
|
|
1d6911c476
|
||
|
|
05621aebd2
|
No files matched your search
@@ -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
|
||||||
|
for _ in $(seq 1 24); do
|
||||||
|
code="$(curl -sS -o "$RUNNER_TEMP/served.pkg" -w '%{http_code}' "$url" || true)"
|
||||||
|
if [ "$code" = 200 ]; then
|
||||||
|
served="$(sha256sum "$RUNNER_TEMP/served.pkg" | cut -d' ' -f1)"
|
||||||
|
if [ "$served" = "$expected" ]; then
|
||||||
echo "published $url"
|
echo "published $url"
|
||||||
exit 0
|
exit 0
|
||||||
fi
|
fi
|
||||||
|
echo "::error::$url serves sha256 $served instead of $expected"
|
||||||
|
echo "::error::the CDN is still caching another build under this name: purge it before re-running"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
sleep 5
|
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
|
||||||
@@ -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.6`), pas la version amont de kitty embarquée dans le paquet :
|
du fork FWS (`0.1.11`), 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.6-2` remplace alors le
|
(*Actions → Release → Run workflow*) : le paquet `0.1.8-2` remplace alors le
|
||||||
`0.1.6-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
|
||||||
|
|||||||
+16
-3
@@ -12,9 +12,9 @@ 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)
|
||||||
@@ -26,7 +26,20 @@ Next shell prompt :sc:`scroll_to_next_prompt` (see :ref:`shell_integra
|
|||||||
Browse scrollback in less :sc:`show_scrollback`
|
Browse scrollback in less :sc:`show_scrollback`
|
||||||
Browse last cmd output :sc:`show_last_command_output` (see :ref:`shell_integration`)
|
Browse last cmd output :sc:`show_last_command_output` (see :ref:`shell_integration`)
|
||||||
Search scrollback in less :sc:`search_scrollback` (also :kbd:`⌘+F` on macOS)
|
Search scrollback in less :sc:`search_scrollback` (also :kbd:`⌘+F` on macOS)
|
||||||
========================= =======================
|
Search scrollback in place :sc:`search_scrollback_prompt`
|
||||||
|
========================== =======================
|
||||||
|
|
||||||
|
The in-place search highlights every match without replacing the screen with a
|
||||||
|
pager. Prefix the query with ``\c`` to match case sensitively and with ``\r``
|
||||||
|
to use a regular expression; both modifiers can be combined. Write a doubled
|
||||||
|
backslash (``\\c``, ``\\r``) to search for those prefixes literally. While the search
|
||||||
|
is active, :kbd:`n` jumps to the next match, :kbd:`N` to the previous one and
|
||||||
|
:kbd:`Escape` ends it. The ``[current/total]`` counter is shown in the window
|
||||||
|
title, matches use the first mark color (see :opt:`mark1_foreground`) and the
|
||||||
|
current match uses the second one (:opt:`mark2_foreground`), so it stands out
|
||||||
|
from the other matches.
|
||||||
|
The :ac:`scrollback_search_next`, :ac:`scrollback_search_prev` and
|
||||||
|
:ac:`clear_scrollback_search` actions can also be mapped directly.
|
||||||
|
|
||||||
The scroll actions only take effect when the terminal is in the main screen.
|
The scroll actions only take effect when the terminal is in the main screen.
|
||||||
When the alternate screen is active (for example when using a full screen
|
When the alternate screen is active (for example when using a full screen
|
||||||
|
|||||||
+2
-2
@@ -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
@@ -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
|
||||||
|
|||||||
@@ -273,6 +273,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
|
||||||
|
|||||||
+12
-6
@@ -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
@@ -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
@@ -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
@@ -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
|
||||||
|
|
||||||
|
|||||||
@@ -102,12 +102,38 @@ The following keys are available while the command palette is open:
|
|||||||
- Jump to the last result
|
- Jump to the last result
|
||||||
* - :kbd:`Backspace`
|
* - :kbd:`Backspace`
|
||||||
- Delete the last character from the query
|
- Delete the last character from the query
|
||||||
|
* - :kbd:`Ctrl+R`
|
||||||
|
- Remap the selected action by pressing its new shortcut
|
||||||
* - :kbd:`F12`
|
* - :kbd:`F12`
|
||||||
- Toggle display of unmapped actions
|
- Toggle display of unmapped actions
|
||||||
* - Mouse click
|
* - Mouse click
|
||||||
- Select and run the clicked action
|
- Select and run the clicked action
|
||||||
|
|
||||||
|
|
||||||
|
Remapping a shortcut
|
||||||
|
----------------------
|
||||||
|
|
||||||
|
Each row shows the shortcut bound to the action in its key column. Select an
|
||||||
|
action and press :kbd:`Ctrl+R`, then press the new shortcut. The palette appends
|
||||||
|
the corresponding :code:`map` directive to :file:`kitty.conf` and reloads the
|
||||||
|
configuration, so the change takes effect immediately without restarting
|
||||||
|
|kitty|. Existing lines are left untouched and the new mapping is appended, so
|
||||||
|
the most recent mapping wins. The read-only shortcuts panel does not offer
|
||||||
|
remapping, and mouse bindings cannot be remapped this way.
|
||||||
|
|
||||||
|
|
||||||
|
Leader key tree
|
||||||
|
-----------------
|
||||||
|
|
||||||
|
When the :opt:`leader` option is set and a multi-key mapping starts with the
|
||||||
|
leader key, pressing it opens the palette in which-key mode. Only the
|
||||||
|
continuations available under the leader prefix are listed, with their help
|
||||||
|
text. Press the key shown in the key column to run that action immediately, or
|
||||||
|
use the arrow keys and :kbd:`Enter`. This mode does not remap or run unmapped
|
||||||
|
actions, it is purely a keyboard tree. See :ref:`leader_keymap` for the
|
||||||
|
configuration example.
|
||||||
|
|
||||||
|
|
||||||
Unmapped actions
|
Unmapped actions
|
||||||
------------------
|
------------------
|
||||||
|
|
||||||
|
|||||||
@@ -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.
|
||||||
@@ -232,6 +235,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
|
||||||
|
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ défaut).
|
|||||||
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+H` dans
|
||||||
n'importe quelle fenêtre ::
|
n'importe quelle fenêtre ::
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
.. _kittens:
|
.. _kittens:
|
||||||
|
|
||||||
Étendre avec les kittens
|
Étendre avec les kittens
|
||||||
-----------------------
|
------------------------
|
||||||
|
|
||||||
.. toctree::
|
.. toctree::
|
||||||
:hidden:
|
:hidden:
|
||||||
|
|||||||
+3
-3
@@ -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
|
||||||
@@ -428,11 +428,61 @@ below::
|
|||||||
map --new-mode XXX --on-action end ...
|
map --new-mode XXX --on-action end ...
|
||||||
|
|
||||||
|
|
||||||
|
.. _leader_keymap:
|
||||||
|
|
||||||
|
Leader key and which-key hints
|
||||||
|
-----------------------------------
|
||||||
|
|
||||||
|
The leader key turns a group of multi-key mappings into a discoverable tree.
|
||||||
|
Set :opt:`leader` to the prefix you want to use, then define mappings that
|
||||||
|
start with that prefix::
|
||||||
|
|
||||||
|
leader ctrl+space
|
||||||
|
|
||||||
|
map ctrl+space>n new_os_window
|
||||||
|
map ctrl+space>w new_window
|
||||||
|
map ctrl+space>t new_tab
|
||||||
|
map ctrl+space>c close_window
|
||||||
|
|
||||||
|
Pressing :kbd:`Ctrl+Space` immediately opens a panel listing every key that can
|
||||||
|
follow, with the action it runs and its help text. Press the key shown in the
|
||||||
|
first column to run the action directly, or use the arrow keys and
|
||||||
|
:kbd:`Enter`/ :kbd:`Escape` to leave. No timeout is needed: the panel opens as
|
||||||
|
soon as the leader key is pressed.
|
||||||
|
|
||||||
|
The panel reads the same structured mapping data as the :doc:`command palette
|
||||||
|
</kittens/command-palette>` and :doc:`the shortcuts help panel
|
||||||
|
</kittens/help>`, so every action they list is also available here. Bindings
|
||||||
|
guarded by :code:`--when-focus-on` are filtered against the focused window
|
||||||
|
before they are shown.
|
||||||
|
|
||||||
|
The leader key is only intercepted when multi-key mappings actually start with
|
||||||
|
it. Otherwise it is passed to the program running in the window normally. Set
|
||||||
|
:opt:`leader` to :code:`none` to disable the panel.
|
||||||
|
|
||||||
|
|
||||||
All mappable actions
|
All mappable actions
|
||||||
------------------------
|
------------------------
|
||||||
|
|
||||||
There is a list of :doc:`all mappable actions <actions>`.
|
There is a list of :doc:`all mappable actions <actions>`.
|
||||||
|
|
||||||
|
Remapping from the command palette
|
||||||
|
----------------------------------
|
||||||
|
|
||||||
|
Every entry in the command palette shows the shortcut currently bound to it.
|
||||||
|
Select an action and press :kbd:`Ctrl+R` to remap it: the footer asks for the
|
||||||
|
new shortcut, so press the key combination you want. The palette appends a
|
||||||
|
:code:`map` directive to :file:`kitty.conf` and reloads the configuration, so
|
||||||
|
the new shortcut is active immediately::
|
||||||
|
|
||||||
|
map ctrl+alt+n new_os_window
|
||||||
|
|
||||||
|
The change is appended to the end of the file, it never rewrites existing lines.
|
||||||
|
A later mapping for the same key wins, as usual in :file:`kitty.conf`. Remove
|
||||||
|
the line manually to undo the change. Remapping is disabled in the read-only
|
||||||
|
shortcuts help panel and for mouse bindings.
|
||||||
|
|
||||||
|
|
||||||
Debugging mapping issues
|
Debugging mapping issues
|
||||||
------------------------------
|
------------------------------
|
||||||
|
|
||||||
|
|||||||
+4
-4
@@ -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
|
||||||
|
|||||||
@@ -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
@@ -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
|
||||||
|
|||||||
@@ -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
@@ -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
|
||||||
|
|||||||
@@ -38,6 +38,15 @@ type InputData struct {
|
|||||||
Mouse []Binding `json:"mouse"`
|
Mouse []Binding `json:"mouse"`
|
||||||
ModeOrder []string `json:"mode_order"`
|
ModeOrder []string `json:"mode_order"`
|
||||||
CategoryOrder map[string][]string `json:"category_order"`
|
CategoryOrder map[string][]string `json:"category_order"`
|
||||||
|
Leader *LeaderData `json:"leader"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// LeaderData is the which-key tree shown when the configured leader key is
|
||||||
|
// pressed. Key holds the key to press after the leader, not the full shortcut.
|
||||||
|
type LeaderData struct {
|
||||||
|
Prefix string `json:"prefix"`
|
||||||
|
Title string `json:"title"`
|
||||||
|
Bindings []Binding `json:"bindings"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// wordToken represents a single word extracted from column text, with its
|
// wordToken represents a single word extracted from column text, with its
|
||||||
@@ -277,6 +286,11 @@ type Handler struct {
|
|||||||
keyboard_shortcuts []*config.KeyAction
|
keyboard_shortcuts []*config.KeyAction
|
||||||
read_only bool
|
read_only bool
|
||||||
data_file string
|
data_file string
|
||||||
|
leader *LeaderData
|
||||||
|
remap_mode bool
|
||||||
|
remap_binding *Binding
|
||||||
|
remap_key string
|
||||||
|
remap_action string
|
||||||
}
|
}
|
||||||
|
|
||||||
// initialize sets up the TUI: screen size, cursor, cached settings, and initial data load.
|
// initialize sets up the TUI: screen size, cursor, cached settings, and initial data load.
|
||||||
@@ -293,11 +307,20 @@ func (h *Handler) initialize() (string, error) {
|
|||||||
if h.read_only {
|
if h.read_only {
|
||||||
title = "Keyboard shortcuts"
|
title = "Keyboard shortcuts"
|
||||||
}
|
}
|
||||||
|
if h.input_data.Leader != nil {
|
||||||
|
title = h.input_data.Leader.Title
|
||||||
|
if title == "" {
|
||||||
|
title = "Leader keys"
|
||||||
|
}
|
||||||
|
}
|
||||||
h.lp.SetWindowTitle(title)
|
h.lp.SetWindowTitle(title)
|
||||||
|
|
||||||
if h.read_only {
|
if h.read_only {
|
||||||
// A reference panel is about bindings, not about actions without one.
|
// A reference panel is about bindings, not about actions without one.
|
||||||
h.show_unmapped = false
|
h.show_unmapped = false
|
||||||
|
} else if h.input_data.Leader != nil {
|
||||||
|
// The leader panel lists exactly the keys that are available.
|
||||||
|
h.show_unmapped = true
|
||||||
} else {
|
} else {
|
||||||
// Initialize with ShowUnmapped: true as the default; Load() returns this
|
// Initialize with ShowUnmapped: true as the default; Load() returns this
|
||||||
// default when no cache file exists yet.
|
// default when no cache file exists yet.
|
||||||
@@ -350,10 +373,26 @@ func (h *Handler) parseData(data []byte) error {
|
|||||||
return fmt.Errorf("failed to parse input data: %w", err)
|
return fmt.Errorf("failed to parse input data: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if h.input_data.Leader != nil {
|
||||||
|
h.leader = h.input_data.Leader
|
||||||
|
h.flattenLeaderBindings()
|
||||||
|
return nil
|
||||||
|
}
|
||||||
h.flattenBindings()
|
h.flattenBindings()
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// flattenLeaderBindings turns the leader tree produced by Python into display
|
||||||
|
// items. The key column already holds only the key to press after the leader.
|
||||||
|
func (h *Handler) flattenLeaderBindings() {
|
||||||
|
for _, b := range h.input_data.Leader.Bindings {
|
||||||
|
b.Category = "Leader"
|
||||||
|
b.Mode = ""
|
||||||
|
b.IsMouse = false
|
||||||
|
h.all_items = append(h.all_items, bindingToDisplayItem(b))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// bindingToDisplayItem converts a Binding into a DisplayItem with pre-tokenized
|
// bindingToDisplayItem converts a Binding into a DisplayItem with pre-tokenized
|
||||||
// words for word-level matching.
|
// words for word-level matching.
|
||||||
func bindingToDisplayItem(b Binding) DisplayItem {
|
func bindingToDisplayItem(b Binding) DisplayItem {
|
||||||
@@ -595,7 +634,9 @@ func (h *Handler) draw_screen() {
|
|||||||
h.lp.QueueWriteString(h.query)
|
h.lp.QueueWriteString(h.query)
|
||||||
|
|
||||||
// Draw results
|
// Draw results
|
||||||
if h.query == "" {
|
if h.leader != nil {
|
||||||
|
h.drawFlatResults(resultsStartY, resultsHeight, width)
|
||||||
|
} else if h.query == "" {
|
||||||
h.drawGroupedResults(resultsStartY, resultsHeight, width)
|
h.drawGroupedResults(resultsStartY, resultsHeight, width)
|
||||||
} else {
|
} else {
|
||||||
h.drawFlatResults(resultsStartY, resultsHeight, width)
|
h.drawFlatResults(resultsStartY, resultsHeight, width)
|
||||||
@@ -615,12 +656,24 @@ func (h *Handler) draw_screen() {
|
|||||||
unmappedToggleLabel = "Hide"
|
unmappedToggleLabel = "Hide"
|
||||||
}
|
}
|
||||||
footer := ""
|
footer := ""
|
||||||
|
if h.leader != nil {
|
||||||
|
footer = h.lp.SprintStyled("fg=bright-yellow", "[Esc]") + " Close " +
|
||||||
|
h.lp.SprintStyled("fg=bright-yellow", "\u2191\u2193") + " Navigate " +
|
||||||
|
h.lp.SprintStyled("fg=bright-yellow", "[Enter]") + " Run or press the next key"
|
||||||
|
} else if h.remap_mode {
|
||||||
|
footer = h.lp.SprintStyled("fg=bright-yellow", "Press the new shortcut") + " " +
|
||||||
|
h.lp.SprintStyled("fg=bright-yellow", "[Esc]") + " Cancel"
|
||||||
|
} else {
|
||||||
if !h.read_only {
|
if !h.read_only {
|
||||||
footer = h.lp.SprintStyled("fg=bright-yellow", "[Enter]") + " Run "
|
footer = h.lp.SprintStyled("fg=bright-yellow", "[Enter]") + " Run "
|
||||||
}
|
}
|
||||||
footer += h.lp.SprintStyled("fg=bright-yellow", "[Esc]") + " Quit " +
|
footer += h.lp.SprintStyled("fg=bright-yellow", "[Esc]") + " Quit " +
|
||||||
h.lp.SprintStyled("fg=bright-yellow", "\u2191\u2193") + " Navigate " +
|
h.lp.SprintStyled("fg=bright-yellow", "\u2191\u2193") + " Navigate " +
|
||||||
h.lp.SprintStyled("fg=bright-yellow", "[F12]") + " " + unmappedToggleLabel + " unmapped"
|
h.lp.SprintStyled("fg=bright-yellow", "[F12]") + " " + unmappedToggleLabel + " unmapped"
|
||||||
|
if !h.read_only {
|
||||||
|
footer += " " + h.lp.SprintStyled("fg=bright-yellow", "[Ctrl+R]") + " Remap"
|
||||||
|
}
|
||||||
|
}
|
||||||
matchCount := ""
|
matchCount := ""
|
||||||
if h.query != "" {
|
if h.query != "" {
|
||||||
matchCount = fmt.Sprintf(" %d/%d", len(h.filtered_idx), len(h.all_items))
|
matchCount = fmt.Sprintf(" %d/%d", len(h.filtered_idx), len(h.all_items))
|
||||||
@@ -695,7 +748,9 @@ func (h *Handler) drawFlatResults(startY, maxRows, width int) {
|
|||||||
b := &item.binding
|
b := &item.binding
|
||||||
keyDisplay := keyDisplayText(b)
|
keyDisplay := keyDisplayText(b)
|
||||||
catSuffix := ""
|
catSuffix := ""
|
||||||
if b.Mode != "" {
|
if h.leader != nil {
|
||||||
|
// Leader rows have no category to disambiguate.
|
||||||
|
} else if b.Mode != "" {
|
||||||
catSuffix = fmt.Sprintf(" [%s/%s]", b.Mode, b.Category)
|
catSuffix = fmt.Sprintf(" [%s/%s]", b.Mode, b.Category)
|
||||||
} else {
|
} else {
|
||||||
catSuffix = fmt.Sprintf(" [%s]", b.Category)
|
catSuffix = fmt.Sprintf(" [%s]", b.Category)
|
||||||
@@ -861,14 +916,14 @@ func (h *Handler) drawBindingLine(filteredIdx, width int, isSelected bool) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Render category suffix (only present in flat / search-results mode)
|
// Render category suffix (only present in flat / search-results mode)
|
||||||
if h.query != "" {
|
if h.query != "" && h.leader == nil {
|
||||||
h.drawCategorySuffix(b, mi, baseStyle, matchStyle)
|
h.drawCategorySuffix(b, mi, baseStyle, matchStyle)
|
||||||
}
|
}
|
||||||
|
|
||||||
// For selected rows, pad the rest of the line with reverse video
|
// For selected rows, pad the rest of the line with reverse video
|
||||||
if isSelected {
|
if isSelected {
|
||||||
rendered := 4 + wcswidth.Stringwidth(keyDisplay) + paddingLen + 1 + wcswidth.Stringwidth(actionDisplay)
|
rendered := 4 + wcswidth.Stringwidth(keyDisplay) + paddingLen + 1 + wcswidth.Stringwidth(actionDisplay)
|
||||||
if h.query != "" {
|
if h.query != "" && h.leader == nil {
|
||||||
rendered += categorySuffixWidth(b)
|
rendered += categorySuffixWidth(b)
|
||||||
}
|
}
|
||||||
if pad := width - rendered; pad > 0 {
|
if pad := width - rendered; pad > 0 {
|
||||||
@@ -916,6 +971,25 @@ func (h *Handler) onMouseEvent(ev *loop.MouseEvent) error {
|
|||||||
|
|
||||||
// onKeyEvent handles keyboard input for navigation, selection, and query editing.
|
// onKeyEvent handles keyboard input for navigation, selection, and query editing.
|
||||||
func (h *Handler) onKeyEvent(ev *loop.KeyEvent) error {
|
func (h *Handler) onKeyEvent(ev *loop.KeyEvent) error {
|
||||||
|
if h.remap_mode {
|
||||||
|
ev.Handled = true
|
||||||
|
if ev.MatchesPressOrRepeat("escape") || ev.MatchesPressOrRepeat("ctrl+c") {
|
||||||
|
h.remap_mode, h.remap_binding = false, nil
|
||||||
|
h.draw_screen()
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if ev.Type&(loop.PRESS|loop.REPEAT) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
spec := keySpecForRemap(ev)
|
||||||
|
if spec == "" || h.remap_binding == nil {
|
||||||
|
h.lp.Beep()
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
h.remap_key, h.remap_action = spec, h.remap_binding.Definition
|
||||||
|
h.lp.Quit(0)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
if ev.MatchesPressOrRepeat("escape") {
|
if ev.MatchesPressOrRepeat("escape") {
|
||||||
ev.Handled = true
|
ev.Handled = true
|
||||||
if h.query != "" {
|
if h.query != "" {
|
||||||
@@ -996,6 +1070,24 @@ func (h *Handler) onKeyEvent(ev *loop.KeyEvent) error {
|
|||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
if ev.MatchesPressOrRepeat("ctrl+r") && !h.read_only && h.leader == nil {
|
||||||
|
ev.Handled = true
|
||||||
|
if b := h.selectedBinding(); b != nil && !b.IsMouse {
|
||||||
|
h.remap_mode, h.remap_binding = true, b
|
||||||
|
h.draw_screen()
|
||||||
|
} else {
|
||||||
|
h.lp.Beep()
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if h.leader != nil {
|
||||||
|
if b := h.matchLeaderBinding(ev); b != nil {
|
||||||
|
ev.Handled = true
|
||||||
|
h.leader_trigger(b)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
if ev.MatchesPressOrRepeat("f12") {
|
if ev.MatchesPressOrRepeat("f12") {
|
||||||
ev.Handled = true
|
ev.Handled = true
|
||||||
h.show_unmapped = !h.show_unmapped
|
h.show_unmapped = !h.show_unmapped
|
||||||
@@ -1010,8 +1102,19 @@ func (h *Handler) onKeyEvent(ev *loop.KeyEvent) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// onText handles typed characters, appending them to the search query.
|
// onText handles typed characters, appending them to the search query, or
|
||||||
|
// running the binding whose key was typed in the leader panel.
|
||||||
func (h *Handler) onText(text string, from_key_event bool, in_bracketed_paste bool) error {
|
func (h *Handler) onText(text string, from_key_event bool, in_bracketed_paste bool) error {
|
||||||
|
if h.leader != nil {
|
||||||
|
for i := range h.all_items {
|
||||||
|
if b := &h.all_items[i].binding; b.Key != "" && strings.EqualFold(b.Key, text) {
|
||||||
|
h.leader_trigger(b)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
h.lp.Beep()
|
||||||
|
return nil
|
||||||
|
}
|
||||||
h.query += text
|
h.query += text
|
||||||
h.updateFilter()
|
h.updateFilter()
|
||||||
h.draw_screen()
|
h.draw_screen()
|
||||||
@@ -1036,6 +1139,49 @@ func (h *Handler) moveSelection(delta int) {
|
|||||||
h.draw_screen()
|
h.draw_screen()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// matchLeaderBinding finds the leader entry whose key matches the event.
|
||||||
|
func (h *Handler) matchLeaderBinding(ev *loop.KeyEvent) *Binding {
|
||||||
|
for i := range h.all_items {
|
||||||
|
if b := &h.all_items[i].binding; b.Key != "" && ev.MatchesPressOrRepeat(b.Key) {
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// leader_trigger runs a leader entry immediately, without waiting for the rest
|
||||||
|
// of a longer multi-key sequence.
|
||||||
|
func (h *Handler) leader_trigger(b *Binding) {
|
||||||
|
h.result = b.Definition
|
||||||
|
h.lp.Quit(0)
|
||||||
|
}
|
||||||
|
|
||||||
|
// keySpecForRemap renders a key event in kitty.conf syntax so that the palette
|
||||||
|
// can write a map directive for it.
|
||||||
|
func keySpecForRemap(ev *loop.KeyEvent) string {
|
||||||
|
mods := ev.Mods.WithoutLocks()
|
||||||
|
parts := make([]string, 0, 4)
|
||||||
|
for _, m := range []struct {
|
||||||
|
mod loop.KeyModifiers
|
||||||
|
name string
|
||||||
|
}{{loop.CTRL, "ctrl"}, {loop.ALT, "alt"}, {loop.SHIFT, "shift"}, {loop.SUPER, "super"}, {loop.HYPER, "hyper"}, {loop.META, "meta"}} {
|
||||||
|
if mods&m.mod != 0 {
|
||||||
|
parts = append(parts, m.name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
key := ev.Key
|
||||||
|
if key == "" {
|
||||||
|
key = ev.Text
|
||||||
|
}
|
||||||
|
if key == "" {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
if len(key) == 1 && key[0] >= 'A' && key[0] <= 'Z' {
|
||||||
|
key = strings.ToLower(key)
|
||||||
|
}
|
||||||
|
return strings.Join(append(parts, key), "+")
|
||||||
|
}
|
||||||
|
|
||||||
// triggerSelected sets the selected binding's definition as the result and exits.
|
// triggerSelected sets the selected binding's definition as the result and exits.
|
||||||
func (h *Handler) triggerSelected() {
|
func (h *Handler) triggerSelected() {
|
||||||
if h.read_only {
|
if h.read_only {
|
||||||
@@ -1085,7 +1231,12 @@ func main(cmd *cli.Command, opts *Options, args []string) (rc int, err error) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
rc = lp.ExitCode()
|
rc = lp.ExitCode()
|
||||||
if handler.result != "" {
|
if handler.remap_key != "" {
|
||||||
|
s, serr := output(map[string]string{"remap_key": handler.remap_key, "remap_action": handler.remap_action})
|
||||||
|
if serr == nil {
|
||||||
|
fmt.Println(s)
|
||||||
|
}
|
||||||
|
} else if handler.result != "" {
|
||||||
s, serr := output(map[string]string{"action": handler.result})
|
s, serr := output(map[string]string{"action": handler.result})
|
||||||
if serr == nil {
|
if serr == nil {
|
||||||
fmt.Println(s)
|
fmt.Println(s)
|
||||||
|
|||||||
@@ -318,6 +318,52 @@ def collect_keys_data(opts: Any) -> dict[str, Any]:
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def collect_leader_data(opts: Any, prefix: Any, definitions: Any = None) -> dict[str, Any]:
|
||||||
|
"""Build the data for the leader/which-key panel from sequence mappings.
|
||||||
|
|
||||||
|
Only the first key after the leader is listed: that is the key the user has
|
||||||
|
to press next, matching how which-key panels present prefix trees. When the
|
||||||
|
mapping needs more keys, the full definition is still shown in the action
|
||||||
|
column and selecting it runs the action directly.
|
||||||
|
"""
|
||||||
|
from kitty.types import Shortcut
|
||||||
|
|
||||||
|
action_to_group, action_to_help, action_to_long_help = build_action_lookups()
|
||||||
|
if definitions is None:
|
||||||
|
definitions = []
|
||||||
|
for defns in opts.keyboard_modes[''].keymap.values():
|
||||||
|
for d in defns:
|
||||||
|
if d.is_sequence and d.trigger == prefix:
|
||||||
|
definitions.append(d)
|
||||||
|
|
||||||
|
bindings: list[dict[str, str]] = []
|
||||||
|
seen: set[str] = set()
|
||||||
|
for d in definitions:
|
||||||
|
if not d.is_sequence or not d.rest:
|
||||||
|
continue
|
||||||
|
key_repr = Shortcut((d.rest[0],)).human_repr(opts.kitty_mod)
|
||||||
|
if key_repr in seen:
|
||||||
|
continue
|
||||||
|
seen.add(key_repr)
|
||||||
|
action_name, category, alias = classify_action(d.definition, opts.alias_map, action_to_group)
|
||||||
|
entry: dict[str, str] = {
|
||||||
|
'key': key_repr,
|
||||||
|
'action': action_name,
|
||||||
|
'action_display': d.human_repr(),
|
||||||
|
'definition': d.definition,
|
||||||
|
'help': action_to_help.get(action_name, ''),
|
||||||
|
'long_help': action_to_long_help.get(action_name, ''),
|
||||||
|
'category': category,
|
||||||
|
}
|
||||||
|
if alias:
|
||||||
|
entry['alias'] = alias
|
||||||
|
bindings.append(entry)
|
||||||
|
bindings.sort(key=lambda b: b['key'])
|
||||||
|
prefix_repr = Shortcut((prefix,)).human_repr(opts.kitty_mod) if prefix is not None else ''
|
||||||
|
title = f'Leader keys ({prefix_repr})' if prefix_repr else 'Leader keys'
|
||||||
|
return {'leader': {'prefix': prefix_repr, 'title': title, 'bindings': bindings}}
|
||||||
|
|
||||||
|
|
||||||
def main(args: list[str]) -> None:
|
def main(args: list[str]) -> None:
|
||||||
raise SystemExit('This kitten must be used only from a kitty.conf mapping')
|
raise SystemExit('This kitten must be used only from a kitty.conf mapping')
|
||||||
|
|
||||||
@@ -330,7 +376,21 @@ def callback(target_window_id: int, action: str, timer_id: int | None) -> None:
|
|||||||
|
|
||||||
@result_handler(has_ready_notification=True)
|
@result_handler(has_ready_notification=True)
|
||||||
def handle_result(args: list[str], data: dict[str, Any], target_window_id: int, boss: BossType) -> None:
|
def handle_result(args: list[str], data: dict[str, Any], target_window_id: int, boss: BossType) -> None:
|
||||||
if data and (action := data.get('action')):
|
if not data:
|
||||||
|
return
|
||||||
|
remap_key, remap_action = data.get('remap_key'), data.get('remap_action')
|
||||||
|
if remap_key and remap_action:
|
||||||
|
from kitty.config import append_map_to_config
|
||||||
|
|
||||||
|
try:
|
||||||
|
path = append_map_to_config(remap_key, remap_action)
|
||||||
|
boss.load_config_file()
|
||||||
|
except Exception as err:
|
||||||
|
boss.show_error('Failed to remap shortcut', f'Could not update {remap_key} in the config file: {err}')
|
||||||
|
else:
|
||||||
|
print(f'Mapped {remap_key} to {remap_action} in {path}', flush=True)
|
||||||
|
return
|
||||||
|
if action := data.get('action'):
|
||||||
# run action after event loop tick so command palette overlay is closed
|
# run action after event loop tick so command palette overlay is closed
|
||||||
add_timer(partial(callback, target_window_id, action), 0, False)
|
add_timer(partial(callback, target_window_id, action), 0, False)
|
||||||
|
|
||||||
|
|||||||
@@ -5,6 +5,8 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"github.com/kovidgoyal/kitty/tools/tui/loop"
|
||||||
)
|
)
|
||||||
|
|
||||||
// testBinding creates a Binding where Action, ActionDisplay, and Definition all
|
// testBinding creates a Binding where Action, ActionDisplay, and Definition all
|
||||||
@@ -120,6 +122,48 @@ func newTestHandler() *Handler {
|
|||||||
build()
|
build()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestLeaderPanel(t *testing.T) {
|
||||||
|
h := &Handler{}
|
||||||
|
data := []byte(`{"leader":{"prefix":"ctrl+space","title":"Leader keys","bindings":[{"key":"n","action":"new_os_window","action_display":"new_os_window","definition":"new_os_window"},{"key":"shift+w","action":"new_window","action_display":"new_window","definition":"new_window"}]}}`)
|
||||||
|
if err := h.parseData(data); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if h.leader == nil {
|
||||||
|
t.Fatal("expected leader mode to be active")
|
||||||
|
}
|
||||||
|
if len(h.all_items) != 2 {
|
||||||
|
t.Fatalf("expected 2 leader entries, got %d", len(h.all_items))
|
||||||
|
}
|
||||||
|
if b := h.matchLeaderBinding(&loop.KeyEvent{Type: loop.PRESS, Key: "n"}); b == nil || b.Definition != "new_os_window" {
|
||||||
|
t.Fatalf("expected n to run new_os_window, got %+v", b)
|
||||||
|
}
|
||||||
|
if b := h.matchLeaderBinding(&loop.KeyEvent{Type: loop.PRESS, Key: "w", Mods: loop.SHIFT, ShiftedKey: "W"}); b == nil || b.Definition != "new_window" {
|
||||||
|
t.Fatalf("expected shift+w to run new_window, got %+v", b)
|
||||||
|
}
|
||||||
|
if b := h.matchLeaderBinding(&loop.KeyEvent{Type: loop.PRESS, Key: "x"}); b != nil {
|
||||||
|
t.Fatalf("expected x to match nothing, got %+v", b)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestKeySpecForRemap(t *testing.T) {
|
||||||
|
cases := []struct {
|
||||||
|
ev loop.KeyEvent
|
||||||
|
expected string
|
||||||
|
}{
|
||||||
|
{loop.KeyEvent{Type: loop.PRESS, Key: "a"}, "a"},
|
||||||
|
{loop.KeyEvent{Type: loop.PRESS, Key: "a", Mods: loop.SHIFT}, "shift+a"},
|
||||||
|
{loop.KeyEvent{Type: loop.PRESS, Key: "a", Mods: loop.CTRL | loop.SHIFT}, "ctrl+shift+a"},
|
||||||
|
{loop.KeyEvent{Type: loop.PRESS, Key: "a", Mods: loop.CTRL | loop.CAPS_LOCK}, "ctrl+a"},
|
||||||
|
{loop.KeyEvent{Type: loop.PRESS, Key: "", Text: "é"}, "é"},
|
||||||
|
{loop.KeyEvent{Type: loop.PRESS, Key: "", Text: ""}, ""},
|
||||||
|
}
|
||||||
|
for _, c := range cases {
|
||||||
|
if got := keySpecForRemap(&c.ev); got != c.expected {
|
||||||
|
t.Fatalf("keySpecForRemap(%+v) = %q, expected %q", c.ev, got, c.expected)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestFlattenAllBindings(t *testing.T) {
|
func TestFlattenAllBindings(t *testing.T) {
|
||||||
h := newTestHandler()
|
h := newTestHandler()
|
||||||
// 5 default mode + 2 mw mode + 2 mouse = 9
|
// 5 default mode + 2 mw mode + 2 mouse = 9
|
||||||
|
|||||||
@@ -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
|
||||||
|
|||||||
@@ -80,6 +80,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 +208,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")
|
||||||
|
|||||||
@@ -2856,6 +2856,15 @@ class Boss:
|
|||||||
data = collect_keys_data(get_options())
|
data = collect_keys_data(get_options())
|
||||||
self.run_kitten_with_metadata('command-palette', input_data=json.dumps(data), window=self.window_for_dispatch)
|
self.run_kitten_with_metadata('command-palette', input_data=json.dumps(data), window=self.window_for_dispatch)
|
||||||
|
|
||||||
|
def show_leader_keymap(self, prefix: Any, definitions: Any = None) -> None:
|
||||||
|
"""Show the keys available under the leader prefix in the palette overlay."""
|
||||||
|
from kittens.command_palette.main import collect_leader_data
|
||||||
|
|
||||||
|
data = collect_leader_data(get_options(), prefix, definitions)
|
||||||
|
if not data['leader']['bindings']:
|
||||||
|
return
|
||||||
|
self.run_kitten_with_metadata('command-palette', input_data=json.dumps(data), window=self.window_for_dispatch)
|
||||||
|
|
||||||
@ac(
|
@ac(
|
||||||
'tab',
|
'tab',
|
||||||
"""
|
"""
|
||||||
|
|||||||
@@ -80,6 +80,45 @@ def prepare_config_file_for_editing() -> str:
|
|||||||
return defconf
|
return defconf
|
||||||
|
|
||||||
|
|
||||||
|
def finalize_leader(opts: Options) -> None:
|
||||||
|
"""Validate the leader shortcut once so that key handling can use it directly."""
|
||||||
|
from .keys import leader_key_from_options
|
||||||
|
|
||||||
|
try:
|
||||||
|
opts.leader_key = leader_key_from_options(opts)
|
||||||
|
except Exception as err:
|
||||||
|
opts.leader_key = None
|
||||||
|
log_error(f'Ignoring invalid leader shortcut: {opts.leader}. Error: {err}')
|
||||||
|
|
||||||
|
|
||||||
|
def append_map_to_config(key: str, definition: str, conf_path: str = '') -> str:
|
||||||
|
"""Append a map directive to the user config, creating it when needed.
|
||||||
|
|
||||||
|
The path is returned so that callers can report it. Only the mapping is
|
||||||
|
written, existing configuration is never rewritten.
|
||||||
|
"""
|
||||||
|
from .constants import config_dir
|
||||||
|
|
||||||
|
path = conf_path or os.path.join(config_dir, 'kitty.conf')
|
||||||
|
parent = os.path.dirname(path)
|
||||||
|
if parent:
|
||||||
|
with suppress(FileExistsError):
|
||||||
|
os.makedirs(parent)
|
||||||
|
needs_newline = False
|
||||||
|
try:
|
||||||
|
if os.path.getsize(path) > 0:
|
||||||
|
with open(path, 'rb') as f:
|
||||||
|
f.seek(-1, os.SEEK_END)
|
||||||
|
needs_newline = f.read(1) != b'\n'
|
||||||
|
except FileNotFoundError:
|
||||||
|
pass
|
||||||
|
with open(path, 'ab') as f:
|
||||||
|
if needs_newline:
|
||||||
|
f.write(b'\n')
|
||||||
|
f.write(f'map {key} {definition}\n'.encode('utf-8'))
|
||||||
|
return path
|
||||||
|
|
||||||
|
|
||||||
def finalize_keys(opts: Options, accumulate_bad_lines: list[BadLine] | None = None) -> None:
|
def finalize_keys(opts: Options, accumulate_bad_lines: list[BadLine] | None = None) -> None:
|
||||||
defns: list[KeyDefinition] = []
|
defns: list[KeyDefinition] = []
|
||||||
for d in opts.map:
|
for d in opts.map:
|
||||||
@@ -118,6 +157,7 @@ def finalize_keys(opts: Options, accumulate_bad_lines: list[BadLine] | None = No
|
|||||||
items = m.keymap[defn.trigger] = [kd for kd in items if defn.rest != kd.rest or defn.options.when_focus_on != kd.options.when_focus_on]
|
items = m.keymap[defn.trigger] = [kd for kd in items if defn.rest != kd.rest or defn.options.when_focus_on != kd.options.when_focus_on]
|
||||||
items.append(defn)
|
items.append(defn)
|
||||||
opts.keyboard_modes = modes
|
opts.keyboard_modes = modes
|
||||||
|
finalize_leader(opts)
|
||||||
|
|
||||||
|
|
||||||
def finalize_mouse_mappings(opts: Options, accumulate_bad_lines: list[BadLine] | None = None) -> None:
|
def finalize_mouse_mappings(opts: Options, accumulate_bad_lines: list[BadLine] | None = None) -> None:
|
||||||
|
|||||||
+32
-1
@@ -23,7 +23,7 @@ from .fast_data_types import (
|
|||||||
set_ignore_os_keyboard_processing,
|
set_ignore_os_keyboard_processing,
|
||||||
)
|
)
|
||||||
from .options.types import Options
|
from .options.types import Options
|
||||||
from .options.utils import KeyboardMode, KeyDefinition, KeyFallbackType, KeyMap, KeyMapOptions
|
from .options.utils import KeyboardMode, KeyDefinition, KeyFallbackType, KeyMap, KeyMapOptions, parse_shortcut
|
||||||
from .typing_compat import ScreenType
|
from .typing_compat import ScreenType
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
@@ -40,6 +40,14 @@ def keyboard_mode_name(screen: ScreenType) -> str:
|
|||||||
return 'application' if screen.cursor_key_mode else 'normal'
|
return 'application' if screen.cursor_key_mode else 'normal'
|
||||||
|
|
||||||
|
|
||||||
|
def leader_key_from_options(opts: Options) -> SingleKey | None:
|
||||||
|
"""The shortcut that opens the leader tree, or None when disabled."""
|
||||||
|
raw = (getattr(opts, 'leader', '') or '').strip()
|
||||||
|
if not raw or raw.lower() in ('none', 'no', 'off'):
|
||||||
|
return None
|
||||||
|
return parse_shortcut(raw)
|
||||||
|
|
||||||
|
|
||||||
def get_shortcut(keymap: KeyMap, ev: KeyEvent) -> list[KeyDefinition] | None:
|
def get_shortcut(keymap: KeyMap, ev: KeyEvent) -> list[KeyDefinition] | None:
|
||||||
mods = ev.mods & mod_mask
|
mods = ev.mods & mod_mask
|
||||||
ans = keymap.get(SingleKey(mods, False, ev.key))
|
ans = keymap.get(SingleKey(mods, False, ev.key))
|
||||||
@@ -111,6 +119,24 @@ class Mappings:
|
|||||||
self.keyboard_modes[''].keymap = km = km.copy()
|
self.keyboard_modes[''].keymap = km = km.copy()
|
||||||
for sc in self.global_shortcuts.values():
|
for sc in self.global_shortcuts.values():
|
||||||
km.pop(sc, None)
|
km.pop(sc, None)
|
||||||
|
self.leader_key: SingleKey | None = getattr(self.get_options(), 'leader_key', None)
|
||||||
|
if self.leader_key is None:
|
||||||
|
try:
|
||||||
|
self.leader_key = leader_key_from_options(self.get_options())
|
||||||
|
except Exception:
|
||||||
|
# An invalid leader is reported when the config is loaded.
|
||||||
|
self.leader_key = None
|
||||||
|
|
||||||
|
def leader_continuations(self, mode: KeyboardMode) -> list[KeyDefinition]:
|
||||||
|
"""Multi-key mappings whose first key is the leader key."""
|
||||||
|
ans: list[KeyDefinition] = []
|
||||||
|
if self.leader_key is None:
|
||||||
|
return ans
|
||||||
|
for defns in mode.keymap.values():
|
||||||
|
for d in defns:
|
||||||
|
if d.is_sequence and d.trigger == self.leader_key:
|
||||||
|
ans.append(d)
|
||||||
|
return ans
|
||||||
|
|
||||||
def clear_keyboard_modes(self) -> None:
|
def clear_keyboard_modes(self) -> None:
|
||||||
had_mode = bool(self.keyboard_mode_stack)
|
had_mode = bool(self.keyboard_mode_stack)
|
||||||
@@ -212,6 +238,11 @@ class Mappings:
|
|||||||
# Handles shortcuts, return True if the key was consumed
|
# Handles shortcuts, return True if the key was consumed
|
||||||
is_root_mode = not self.keyboard_mode_stack
|
is_root_mode = not self.keyboard_mode_stack
|
||||||
mode = self.keyboard_modes[''] if is_root_mode else self.keyboard_mode_stack[-1]
|
mode = self.keyboard_modes[''] if is_root_mode else self.keyboard_mode_stack[-1]
|
||||||
|
if is_root_mode and self.leader_key is not None and shortcut_matches(self.leader_key, ev):
|
||||||
|
continuations = self.matching_key_actions(self.leader_continuations(mode))
|
||||||
|
if continuations:
|
||||||
|
get_boss().show_leader_keymap(self.leader_key, continuations)
|
||||||
|
return True
|
||||||
key_action = get_shortcut(mode.keymap, ev)
|
key_action = get_shortcut(mode.keymap, ev)
|
||||||
if key_action is None and self.global_shortcuts_map and (global_key_action := get_shortcut(self.global_shortcuts_map, ev)) is not None:
|
if key_action is None and self.global_shortcuts_map and (global_key_action := get_shortcut(self.global_shortcuts_map, ev)) is not None:
|
||||||
if grab_keyboard(None):
|
if grab_keyboard(None):
|
||||||
|
|||||||
@@ -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.6\x1b[39m by \x1b[1;34mBlackAngelTV\x1b[22;39m\n");
|
printf("\x1b[3mfws-kitty\x1b[23m \x1b[32m0.1.11\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.6 by BlackAngelTV\n");
|
printf("fws-kitty 0.1.11 by BlackAngelTV\n");
|
||||||
}
|
}
|
||||||
exit(0);
|
exit(0);
|
||||||
}
|
}
|
||||||
|
|||||||
+19
-1
@@ -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 = {}
|
||||||
|
|||||||
@@ -3791,6 +3791,22 @@ this option to alter all default shortcuts that use :opt:`kitty_mod`.
|
|||||||
""",
|
""",
|
||||||
)
|
)
|
||||||
|
|
||||||
|
opt(
|
||||||
|
'leader',
|
||||||
|
'ctrl+space',
|
||||||
|
long_text="""
|
||||||
|
The key that opens the leader key tree. When you press it and there are
|
||||||
|
multi-key mappings starting with this key (for example
|
||||||
|
:code:`map ctrl+space>n new_os_window`), kitty displays every possible
|
||||||
|
continuation with its action and help text, without waiting for a timeout. See
|
||||||
|
:ref:`leader_keymap` for details.
|
||||||
|
|
||||||
|
Set it to :code:`none` to disable the leader key. Only mappings whose first key
|
||||||
|
is the leader key are affected, a leader key with no multi-key mapping behind it
|
||||||
|
is passed through to the program running in kitty.
|
||||||
|
""",
|
||||||
|
)
|
||||||
|
|
||||||
opt(
|
opt(
|
||||||
'remap_modifiers',
|
'remap_modifiers',
|
||||||
'',
|
'',
|
||||||
@@ -4141,6 +4157,21 @@ For more sophisticated control, such as using the current selection, use :ac:`re
|
|||||||
|
|
||||||
map('Search the scrollback within a pager', 'search_scrollback --allow-fallback=shifted,ascii cmd+f search_scrollback', only='macos')
|
map('Search the scrollback within a pager', 'search_scrollback --allow-fallback=shifted,ascii cmd+f search_scrollback', only='macos')
|
||||||
|
|
||||||
|
map(
|
||||||
|
'Search and highlight the scrollback in place',
|
||||||
|
'search_scrollback_prompt kitty_mod+shift+f search_scrollback_prompt',
|
||||||
|
long_text="""
|
||||||
|
Search the scrollback without opening a pager. Every match is highlighted in
|
||||||
|
the scrollback and the ``[current/total]`` counter is shown in the window title.
|
||||||
|
Prefix the query with ``\\c`` to match case sensitively and with ``\\r`` to use
|
||||||
|
a regular expression. While a search is active, :kbd:`n` and :kbd:`N` jump to
|
||||||
|
the next and previous match and :kbd:`Escape` ends the search.
|
||||||
|
|
||||||
|
The :ac:`scrollback_search_next`, :ac:`scrollback_search_prev` and
|
||||||
|
:ac:`clear_scrollback_search` actions can be mapped to other keys.
|
||||||
|
""",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
egr() # }}}
|
egr() # }}}
|
||||||
|
|
||||||
|
|||||||
Generated
+3
@@ -1094,6 +1094,9 @@ class Parser:
|
|||||||
def kitty_mod(self, val: str, ans: dict[str, typing.Any]) -> None:
|
def kitty_mod(self, val: str, ans: dict[str, typing.Any]) -> None:
|
||||||
ans['kitty_mod'] = to_modifiers(val)
|
ans['kitty_mod'] = to_modifiers(val)
|
||||||
|
|
||||||
|
def leader(self, val: str, ans: dict[str, typing.Any]) -> None:
|
||||||
|
ans['leader'] = str(val).strip()
|
||||||
|
|
||||||
def linux_bell_theme(self, val: str, ans: dict[str, typing.Any]) -> None:
|
def linux_bell_theme(self, val: str, ans: dict[str, typing.Any]) -> None:
|
||||||
ans['linux_bell_theme'] = str(val)
|
ans['linux_bell_theme'] = str(val)
|
||||||
|
|
||||||
|
|||||||
Generated
+4
@@ -388,6 +388,7 @@ option_names = (
|
|||||||
'italic_font',
|
'italic_font',
|
||||||
'kitten_alias',
|
'kitten_alias',
|
||||||
'kitty_mod',
|
'kitty_mod',
|
||||||
|
'leader',
|
||||||
'linux_bell_theme',
|
'linux_bell_theme',
|
||||||
'linux_display_server',
|
'linux_display_server',
|
||||||
'listen_on',
|
'listen_on',
|
||||||
@@ -613,6 +614,7 @@ class Options:
|
|||||||
input_delay: int = 3
|
input_delay: int = 3
|
||||||
italic_font: FontSpec = FontSpec(family=None, style=None, postscript_name=None, full_name=None, system='auto', axes=(), variable_name=None, features=(), created_from_string='auto')
|
italic_font: FontSpec = FontSpec(family=None, style=None, postscript_name=None, full_name=None, system='auto', axes=(), variable_name=None, features=(), created_from_string='auto')
|
||||||
kitty_mod: int = 5
|
kitty_mod: int = 5
|
||||||
|
leader: str = 'ctrl+space'
|
||||||
linux_bell_theme: str = '__custom'
|
linux_bell_theme: str = '__custom'
|
||||||
linux_display_server: choices_for_linux_display_server = 'auto'
|
linux_display_server: choices_for_linux_display_server = 'auto'
|
||||||
listen_on: str = 'none'
|
listen_on: str = 'none'
|
||||||
@@ -934,6 +936,8 @@ defaults.map = [
|
|||||||
KeyDefinition(trigger=SingleKey(mods=256, key=103), options=KeyMapOptions(when_focus_on='', new_mode='', mode='', on_unknown='beep', on_action='keep', timeout=None, allow_fallback=(KeyFallbackType.shifted, KeyFallbackType.alternate)), definition='show_last_command_output'),
|
KeyDefinition(trigger=SingleKey(mods=256, key=103), options=KeyMapOptions(when_focus_on='', new_mode='', mode='', on_unknown='beep', on_action='keep', timeout=None, allow_fallback=(KeyFallbackType.shifted, KeyFallbackType.alternate)), definition='show_last_command_output'),
|
||||||
# search_scrollback
|
# search_scrollback
|
||||||
KeyDefinition(trigger=SingleKey(mods=256, key=47), definition='search_scrollback'),
|
KeyDefinition(trigger=SingleKey(mods=256, key=47), definition='search_scrollback'),
|
||||||
|
# search_scrollback_prompt
|
||||||
|
KeyDefinition(trigger=SingleKey(mods=257, key=102), 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
|
||||||
|
|||||||
@@ -0,0 +1,135 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
# License: GPLv3 Copyright: 2026, Kovid Goyal <kovid at kovidgoyal.net>
|
||||||
|
|
||||||
|
"""In-place scrollback search.
|
||||||
|
|
||||||
|
The query parser and the matcher live here, away from the screen code, so that
|
||||||
|
they can be tested without a running terminal. A query can start with two
|
||||||
|
modifiers, in any order: ``\\c`` makes matching case sensitive and ``\\r``
|
||||||
|
treats the query as a regular expression. A doubled backslash escapes the
|
||||||
|
modifier syntax, so that the two prefixes can be searched for literally.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import re
|
||||||
|
from collections.abc import Sequence
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
|
||||||
|
CASE_SENSITIVE_MODIFIER = 'c'
|
||||||
|
REGEX_MODIFIER = 'r'
|
||||||
|
|
||||||
|
# Mark numbers (see :opt:`mark1_background`) used to highlight the matches. The
|
||||||
|
# current match gets its own color so that it stands out from the other ones.
|
||||||
|
MATCH_COLOR = 1
|
||||||
|
CURRENT_MATCH_COLOR = 2
|
||||||
|
|
||||||
|
|
||||||
|
class InvalidQuery(ValueError):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class Query:
|
||||||
|
text: str
|
||||||
|
case_sensitive: bool = False
|
||||||
|
is_regex: bool = False
|
||||||
|
|
||||||
|
@property
|
||||||
|
def flags(self) -> int:
|
||||||
|
return 0 if self.case_sensitive else re.IGNORECASE
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class Match:
|
||||||
|
line: int
|
||||||
|
start: int
|
||||||
|
end: int
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class ScrollbackSearch:
|
||||||
|
query: Query
|
||||||
|
pattern: re.Pattern[str]
|
||||||
|
matches: list[Match] = field(default_factory=list)
|
||||||
|
index: int = 0
|
||||||
|
total_lines: int = 0
|
||||||
|
|
||||||
|
def __len__(self) -> int:
|
||||||
|
return len(self.matches)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def current_match(self) -> Match | None:
|
||||||
|
return self.matches[self.index] if self.matches else None
|
||||||
|
|
||||||
|
def marker_spans(self, lines: Sequence[str]) -> dict[str, tuple[tuple[int, int, int], ...]]:
|
||||||
|
"""Spans to highlight, keyed by the text of the line holding them.
|
||||||
|
|
||||||
|
Marker functions are called once per line with only its text, never with
|
||||||
|
its number, so the spans are grouped by line text. Lines that are
|
||||||
|
identical to the current one are therefore highlighted alike, which the
|
||||||
|
user cannot tell apart since their text is the same.
|
||||||
|
"""
|
||||||
|
current = self.current_match
|
||||||
|
spans: dict[str, list[tuple[int, int, int]]] = {}
|
||||||
|
for match in self.matches:
|
||||||
|
color = CURRENT_MATCH_COLOR if match == current else MATCH_COLOR
|
||||||
|
spans.setdefault(lines[match.line], []).append((match.start, match.end, color))
|
||||||
|
return {text: tuple(found) for text, found in spans.items()}
|
||||||
|
|
||||||
|
|
||||||
|
def parse_query(raw: str) -> Query:
|
||||||
|
text = (raw or '').strip()
|
||||||
|
case_sensitive = is_regex = False
|
||||||
|
while len(text) > 1 and text[0] == '\\':
|
||||||
|
modifier = text[1].lower()
|
||||||
|
if modifier == '\\':
|
||||||
|
# A doubled backslash stands for a literal one and ends the modifier
|
||||||
|
# section, which is the only way to search for \c or \r themselves.
|
||||||
|
text = text[1:]
|
||||||
|
break
|
||||||
|
if modifier == CASE_SENSITIVE_MODIFIER:
|
||||||
|
case_sensitive = True
|
||||||
|
elif modifier == REGEX_MODIFIER:
|
||||||
|
is_regex = True
|
||||||
|
else:
|
||||||
|
# Not a modifier, the backslash is part of the searched text.
|
||||||
|
break
|
||||||
|
text = text[2:]
|
||||||
|
text = text.strip()
|
||||||
|
if not text:
|
||||||
|
raise InvalidQuery('the search query is empty')
|
||||||
|
return Query(text, case_sensitive, is_regex)
|
||||||
|
|
||||||
|
|
||||||
|
def compile_query(query: Query) -> re.Pattern[str]:
|
||||||
|
source = query.text if query.is_regex else re.escape(query.text)
|
||||||
|
try:
|
||||||
|
return re.compile(source, query.flags)
|
||||||
|
except re.error as err:
|
||||||
|
raise InvalidQuery(f'invalid regular expression: {err}') from err
|
||||||
|
|
||||||
|
|
||||||
|
def find_matches(lines: list[str] | tuple[str, ...], query: Query, pattern: re.Pattern[str] | None = None) -> list[Match]:
|
||||||
|
pat = pattern if pattern is not None else compile_query(query)
|
||||||
|
ans: list[Match] = []
|
||||||
|
append = ans.append
|
||||||
|
for line_number, line in enumerate(lines):
|
||||||
|
for match in pat.finditer(line):
|
||||||
|
# Empty matches cannot be navigated to and would make the count
|
||||||
|
# meaningless, so they are ignored.
|
||||||
|
if match.end() > match.start():
|
||||||
|
append(Match(line_number, match.start(), match.end()))
|
||||||
|
return ans
|
||||||
|
|
||||||
|
|
||||||
|
def scroll_offset_for(match: Match, total_lines: int, visible_lines: int) -> int:
|
||||||
|
"""Number of lines to scroll up so that the match is visible.
|
||||||
|
|
||||||
|
The searched text is the history buffer followed by the visible screen, so
|
||||||
|
line 0 is the oldest line. The match is placed roughly a third of the way
|
||||||
|
down the screen, except near the top and bottom of the scrollback.
|
||||||
|
"""
|
||||||
|
history = max(0, total_lines - visible_lines)
|
||||||
|
margin = max(0, visible_lines // 3)
|
||||||
|
return max(0, min(history, history - match.line + margin))
|
||||||
+156
@@ -148,6 +148,7 @@ if TYPE_CHECKING:
|
|||||||
from .fast_data_types import MousePosition
|
from .fast_data_types import MousePosition
|
||||||
from .file_transmission import FileTransmission
|
from .file_transmission import FileTransmission
|
||||||
from .notifications import OnlyWhen
|
from .notifications import OnlyWhen
|
||||||
|
from .scrollback_search import ScrollbackSearch
|
||||||
|
|
||||||
|
|
||||||
class CwdRequestType(Enum):
|
class CwdRequestType(Enum):
|
||||||
@@ -825,6 +826,12 @@ class Window:
|
|||||||
self.actions_on_focus_change: list[Callable[['Window', bool], None]] = []
|
self.actions_on_focus_change: list[Callable[['Window', bool], None]] = []
|
||||||
self.actions_on_removal: list[Callable[['Window'], None]] = []
|
self.actions_on_removal: list[Callable[['Window'], None]] = []
|
||||||
self.current_marker_spec: tuple[str, str | tuple[tuple[int, str], ...]] | None = None
|
self.current_marker_spec: tuple[str, str | tuple[tuple[int, str], ...]] | None = None
|
||||||
|
self.scrollback_search: ScrollbackSearch | None = None
|
||||||
|
self.scrollback_search_spans: dict[str, tuple[tuple[int, int, int], ...]] = {}
|
||||||
|
self.scrollback_search_mode: str = ''
|
||||||
|
self.scrollback_search_saved_marker: tuple[str, str | tuple[tuple[int, str], ...]] | None = None
|
||||||
|
self.scrollback_search_saved_title: str | None = None
|
||||||
|
self.actions_on_focus_change.append(self._on_focus_change_clear_scrollback_search)
|
||||||
self.kitten_result_processors: list[Callable[['Window', Any], None]] = []
|
self.kitten_result_processors: list[Callable[['Window', Any], None]] = []
|
||||||
self.child_is_launched = False
|
self.child_is_launched = False
|
||||||
self.restored_scrollback = b''
|
self.restored_scrollback = b''
|
||||||
@@ -2666,6 +2673,155 @@ class Window:
|
|||||||
w.screen.paste_bytes(sanitized)
|
w.screen.paste_bytes(sanitized)
|
||||||
w.send_key('enter')
|
w.send_key('enter')
|
||||||
|
|
||||||
|
@ac(
|
||||||
|
'sc',
|
||||||
|
"""
|
||||||
|
Search the scrollback in place, highlighting every match. Prefix the query with \\c for a case
|
||||||
|
sensitive search and with \\r for a regular expression. To search for those two strings literally,
|
||||||
|
write a double backslash instead (``\\\\c`` and ``\\\\r``). Matches are navigated with n and N and
|
||||||
|
the search ends with Escape. The [current/total] counter is shown in the window title and the
|
||||||
|
current match uses the second mark color.
|
||||||
|
""",
|
||||||
|
)
|
||||||
|
def search_scrollback_prompt(self) -> bool | None:
|
||||||
|
if not self.screen.is_main_linebuf():
|
||||||
|
return True
|
||||||
|
|
||||||
|
def done(text: str) -> None:
|
||||||
|
if text:
|
||||||
|
self.start_scrollback_search(text)
|
||||||
|
else:
|
||||||
|
self.clear_scrollback_search()
|
||||||
|
|
||||||
|
get_boss().get_line(
|
||||||
|
_(
|
||||||
|
'Search the scrollback. Prefix the query with \\c for a case sensitive search and \\r for a regular expression.'
|
||||||
|
' Write a double backslash to search for those strings literally.'
|
||||||
|
),
|
||||||
|
done,
|
||||||
|
window=self,
|
||||||
|
prompt=_('search> '),
|
||||||
|
window_title=_('Search scrollback'),
|
||||||
|
)
|
||||||
|
return None
|
||||||
|
|
||||||
|
def scrollback_search_lines(self) -> list[str]:
|
||||||
|
# Read the history buffer and the visible screen directly instead of using
|
||||||
|
# as_text(), so that line numbers are the ones scrolling actions use.
|
||||||
|
lines: list[str] = []
|
||||||
|
self.screen.as_text_for_history_buf(lines.append, False, True)
|
||||||
|
self.screen.as_text(lines.append, False, True)
|
||||||
|
return [line.replace('\r', '').replace('\n', '') for line in lines]
|
||||||
|
|
||||||
|
def start_scrollback_search(self, raw_query: str) -> None:
|
||||||
|
from .scrollback_search import InvalidQuery, ScrollbackSearch, compile_query, find_matches, parse_query
|
||||||
|
|
||||||
|
try:
|
||||||
|
query = parse_query(raw_query)
|
||||||
|
pattern = compile_query(query)
|
||||||
|
except InvalidQuery as err:
|
||||||
|
get_boss().show_error(_('Invalid search query'), str(err))
|
||||||
|
return
|
||||||
|
lines = self.scrollback_search_lines()
|
||||||
|
matches = find_matches(lines, query, pattern)
|
||||||
|
if not matches:
|
||||||
|
from .fast_data_types import ring_bell
|
||||||
|
|
||||||
|
ring_bell(self.os_window_id)
|
||||||
|
return
|
||||||
|
self.clear_scrollback_search()
|
||||||
|
|
||||||
|
search = ScrollbackSearch(query, pattern, matches, total_lines=len(lines))
|
||||||
|
self.scrollback_search = search
|
||||||
|
self.scrollback_search_spans = search.marker_spans(lines)
|
||||||
|
self.scrollback_search_saved_marker = self.current_marker_spec
|
||||||
|
self.scrollback_search_saved_title = self.override_title
|
||||||
|
self._push_scrollback_search_mode()
|
||||||
|
self._goto_scrollback_match(0)
|
||||||
|
|
||||||
|
@ac('sc', 'Stop the in-place scrollback search and remove its highlights')
|
||||||
|
def clear_scrollback_search(self) -> None:
|
||||||
|
if self.scrollback_search is None:
|
||||||
|
return
|
||||||
|
self.scrollback_search = None
|
||||||
|
self.scrollback_search_spans = {}
|
||||||
|
self.screen.set_marker()
|
||||||
|
self.current_marker_spec = None
|
||||||
|
saved = self.scrollback_search_saved_marker
|
||||||
|
self.scrollback_search_saved_marker = None
|
||||||
|
if saved is not None:
|
||||||
|
# Restore the marker that was displayed before the search started.
|
||||||
|
from .marks import marker_from_spec
|
||||||
|
|
||||||
|
ftype, spec = saved
|
||||||
|
self.screen.set_marker(marker_from_spec(ftype, spec, 0))
|
||||||
|
self.current_marker_spec = saved
|
||||||
|
self.set_title(self.scrollback_search_saved_title)
|
||||||
|
self.scrollback_search_saved_title = None
|
||||||
|
if self.scrollback_search_mode:
|
||||||
|
get_boss().mappings.pop_keyboard_mode_if_is(self.scrollback_search_mode)
|
||||||
|
self.scrollback_search_mode = ''
|
||||||
|
|
||||||
|
@ac('sc', 'Jump to the next match of the in-place scrollback search')
|
||||||
|
def scrollback_search_next(self) -> bool | None:
|
||||||
|
return self._scrollback_search_step(1)
|
||||||
|
|
||||||
|
@ac('sc', 'Jump to the previous match of the in-place scrollback search')
|
||||||
|
def scrollback_search_prev(self) -> bool | None:
|
||||||
|
return self._scrollback_search_step(-1)
|
||||||
|
|
||||||
|
def _scrollback_search_step(self, step: int) -> bool | None:
|
||||||
|
search = self.scrollback_search
|
||||||
|
if search is None:
|
||||||
|
return None
|
||||||
|
if not self.screen.is_main_linebuf():
|
||||||
|
return True
|
||||||
|
self._goto_scrollback_match(search.index + step)
|
||||||
|
return None
|
||||||
|
|
||||||
|
def _goto_scrollback_match(self, index: int) -> None:
|
||||||
|
from .scrollback_search import scroll_offset_for
|
||||||
|
|
||||||
|
search = self.scrollback_search
|
||||||
|
if search is None or not search.matches:
|
||||||
|
return
|
||||||
|
search.index = index % len(search.matches)
|
||||||
|
match = search.matches[search.index]
|
||||||
|
self.set_title(f'[{search.index + 1}/{len(search.matches)}] {search.query.text}')
|
||||||
|
self._refresh_scrollback_search_marker()
|
||||||
|
self.screen.scroll_to_absolute(scroll_offset_for(match, search.total_lines, self.screen.lines))
|
||||||
|
|
||||||
|
def _refresh_scrollback_search_marker(self) -> None:
|
||||||
|
from .marks import marker_from_spans
|
||||||
|
|
||||||
|
# Clear first, as set_marker() only releases the previous callable when
|
||||||
|
# it is called without one. Marking every line again is needed anyway to
|
||||||
|
# recolor the match that was current until now.
|
||||||
|
self.screen.set_marker()
|
||||||
|
self.screen.set_marker(marker_from_spans(self.scrollback_search_spans))
|
||||||
|
|
||||||
|
def _push_scrollback_search_mode(self) -> None:
|
||||||
|
from .fast_data_types import GLFW_FKEY_ESCAPE, GLFW_MOD_SHIFT
|
||||||
|
from .options.utils import KeyboardMode, KeyDefinition, SingleKey
|
||||||
|
|
||||||
|
km = KeyboardMode('__scrollback_search__')
|
||||||
|
km.on_unknown = 'passthrough'
|
||||||
|
km.on_action = 'keep'
|
||||||
|
next_match = KeyDefinition(definition='scrollback_search_next')
|
||||||
|
prev_match = KeyDefinition(definition='scrollback_search_prev')
|
||||||
|
km.keymap[SingleKey(key=ord('n'))].append(next_match)
|
||||||
|
km.keymap[SingleKey(mods=GLFW_MOD_SHIFT, key=ord('n'))].append(prev_match)
|
||||||
|
km.keymap[SingleKey(mods=GLFW_MOD_SHIFT, key=ord('N'))].append(prev_match)
|
||||||
|
km.keymap[SingleKey(key=GLFW_FKEY_ESCAPE)].append(KeyDefinition(definition='clear_scrollback_search'))
|
||||||
|
self.scrollback_search_mode = km.name
|
||||||
|
get_boss().mappings._push_keyboard_mode(km)
|
||||||
|
|
||||||
|
def _on_focus_change_clear_scrollback_search(self, window: 'Window', focused: bool) -> None:
|
||||||
|
# The n/N bindings live in a temporary keyboard mode, so the search must
|
||||||
|
# end when this window stops being the one receiving keys.
|
||||||
|
if not focused and self.scrollback_search is not None:
|
||||||
|
self.clear_scrollback_search()
|
||||||
|
|
||||||
def show_cmd_output(self, which: CommandOutput, title: str = 'Command output', as_ansi: bool = True, add_wrap_markers: bool = True) -> None:
|
def show_cmd_output(self, which: CommandOutput, title: str = 'Command output', as_ansi: bool = True, add_wrap_markers: bool = True) -> None:
|
||||||
text = self.cmd_output(which, as_ansi=as_ansi, add_wrap_markers=add_wrap_markers)
|
text = self.cmd_output(which, as_ansi=as_ansi, add_wrap_markers=add_wrap_markers)
|
||||||
text = text.replace('\r\n', '\n').replace('\r', '\n')
|
text = text.replace('\r\n', '\n').replace('\r', '\n')
|
||||||
|
|||||||
@@ -279,3 +279,52 @@ class TestCommandPalette(BaseTest):
|
|||||||
def test_unmapped_actions_sorted_order(self):
|
def test_unmapped_actions_sorted_order(self):
|
||||||
# Covered by test_collect_keys_bindings_sorted
|
# Covered by test_collect_keys_bindings_sorted
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
def test_leader_prefix_bindings(self):
|
||||||
|
from kittens.command_palette.main import collect_leader_data
|
||||||
|
from kitty.options.utils import parse_map, parse_shortcut
|
||||||
|
|
||||||
|
opts = self.set_options({'leader': 'ctrl+space'})
|
||||||
|
for spec in ('ctrl+space>n new_os_window', 'ctrl+space>w new_window', 'ctrl+space>n new_os_window'):
|
||||||
|
for kd in parse_map(spec):
|
||||||
|
kd = kd.resolve_and_copy(opts.kitty_mod)
|
||||||
|
opts.keyboard_modes[''].keymap.setdefault(kd.trigger, []).append(kd)
|
||||||
|
|
||||||
|
data = collect_leader_data(opts, parse_shortcut('ctrl+space'))
|
||||||
|
leader = data['leader']
|
||||||
|
self.ae(leader['prefix'], 'ctrl+space')
|
||||||
|
self.ae([b['key'] for b in leader['bindings']], ['n', 'w'], 'Duplicate continuations should collapse')
|
||||||
|
self.ae(leader['bindings'][0]['action'], 'new_os_window')
|
||||||
|
self.ae(leader['bindings'][1]['action'], 'new_window')
|
||||||
|
self.assertTrue(leader['bindings'][0]['help'], 'Bindings should carry their help text')
|
||||||
|
|
||||||
|
def test_leader_option(self):
|
||||||
|
from kitty.keys import leader_key_from_options
|
||||||
|
|
||||||
|
opts = self.set_options({'leader': 'none'})
|
||||||
|
self.assertIsNone(leader_key_from_options(opts))
|
||||||
|
self.assertIsNone(opts.leader_key)
|
||||||
|
|
||||||
|
opts = self.set_options({'leader': 'ctrl+space'})
|
||||||
|
self.assertIsNotNone(leader_key_from_options(opts))
|
||||||
|
self.assertIsNotNone(opts.leader_key)
|
||||||
|
|
||||||
|
def test_append_map_to_config(self):
|
||||||
|
import os
|
||||||
|
import tempfile
|
||||||
|
|
||||||
|
from kitty.config import append_map_to_config
|
||||||
|
|
||||||
|
with tempfile.TemporaryDirectory() as tdir:
|
||||||
|
path = os.path.join(tdir, 'kitty.conf')
|
||||||
|
self.ae(append_map_to_config('ctrl+u', 'new_os_window', path), path)
|
||||||
|
self.ae(append_map_to_config('ctrl+j', 'new_tab', path), path)
|
||||||
|
with open(path) as f:
|
||||||
|
self.ae(f.read().splitlines(), ['map ctrl+u new_os_window', 'map ctrl+j new_tab'])
|
||||||
|
|
||||||
|
# A config file without a trailing newline must not get a mangled line
|
||||||
|
with open(path, 'w') as f:
|
||||||
|
f.write('font_size 12')
|
||||||
|
append_map_to_config('ctrl+k', 'new_window', path)
|
||||||
|
with open(path) as f:
|
||||||
|
self.ae(f.read().splitlines(), ['font_size 12', 'map ctrl+k new_window'])
|
||||||
@@ -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()
|
||||||
@@ -0,0 +1,127 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
# License: GPLv3 Copyright: 2026, Kovid Goyal <kovid at kovidgoyal.net>
|
||||||
|
|
||||||
|
import re
|
||||||
|
import time
|
||||||
|
|
||||||
|
from kitty.scrollback_search import (
|
||||||
|
CURRENT_MATCH_COLOR,
|
||||||
|
MATCH_COLOR,
|
||||||
|
InvalidQuery,
|
||||||
|
Match,
|
||||||
|
ScrollbackSearch,
|
||||||
|
compile_query,
|
||||||
|
find_matches,
|
||||||
|
parse_query,
|
||||||
|
scroll_offset_for,
|
||||||
|
)
|
||||||
|
|
||||||
|
from .base import BaseTest
|
||||||
|
|
||||||
|
|
||||||
|
class TestScrollbackSearch(BaseTest):
|
||||||
|
def test_parse_query(self):
|
||||||
|
q = parse_query('needle')
|
||||||
|
self.ae((q.text, q.case_sensitive, q.is_regex), ('needle', False, False))
|
||||||
|
self.assertTrue(compile_query(q).flags & re.IGNORECASE)
|
||||||
|
|
||||||
|
q = parse_query(' padded ')
|
||||||
|
self.ae(q.text, 'padded')
|
||||||
|
|
||||||
|
def test_parse_query_modifiers(self):
|
||||||
|
q = parse_query('\\c Needle')
|
||||||
|
self.ae((q.text, q.case_sensitive, q.is_regex), ('Needle', True, False))
|
||||||
|
self.ae(compile_query(q).flags & re.IGNORECASE, 0)
|
||||||
|
|
||||||
|
q = parse_query('\\r a.c')
|
||||||
|
self.ae((q.text, q.case_sensitive, q.is_regex), ('a.c', False, True))
|
||||||
|
|
||||||
|
for raw in ('\\r\\c a+b', '\\c\\r a+b', '\\C\\R a+b'):
|
||||||
|
q = parse_query(raw)
|
||||||
|
self.ae((q.text, q.case_sensitive, q.is_regex), ('a+b', True, True), raw)
|
||||||
|
|
||||||
|
with self.assertRaises(InvalidQuery):
|
||||||
|
parse_query('')
|
||||||
|
with self.assertRaises(InvalidQuery):
|
||||||
|
parse_query(' ')
|
||||||
|
with self.assertRaises(InvalidQuery):
|
||||||
|
parse_query('\\c')
|
||||||
|
with self.assertRaises(InvalidQuery):
|
||||||
|
compile_query(parse_query('\\r ('))
|
||||||
|
|
||||||
|
def test_parse_query_escaped_backslash(self):
|
||||||
|
# A doubled backslash searches text starting with a backslash instead of
|
||||||
|
# being read as a modifier, so both modifier prefixes remain reachable.
|
||||||
|
for raw, expected in (('\\\\c', '\\c'), ('\\\\r', '\\r'), ('\\\\C', '\\C'), ('\\\\', '\\')):
|
||||||
|
with self.subTest(raw=raw):
|
||||||
|
q = parse_query(raw)
|
||||||
|
self.ae((q.text, q.case_sensitive, q.is_regex), (expected, False, False))
|
||||||
|
|
||||||
|
# Modifiers still combine with an escaped prefix in the searched text
|
||||||
|
q = parse_query('\\c\\\\r')
|
||||||
|
self.ae((q.text, q.case_sensitive, q.is_regex), ('\\r', True, False))
|
||||||
|
|
||||||
|
# The escaped prefix is matched like any other text, case insensitively
|
||||||
|
# by default, and the case sensitive modifier still applies to it.
|
||||||
|
matches = find_matches(['a \\c b', 'a \\C b'], parse_query('\\\\c'))
|
||||||
|
self.ae([(m.line, m.start, m.end) for m in matches], [(0, 2, 4), (1, 2, 4)])
|
||||||
|
matches = find_matches(['a \\c b', 'a \\C b'], parse_query('\\c\\\\c'))
|
||||||
|
self.ae([(m.line, m.start, m.end) for m in matches], [(0, 2, 4)])
|
||||||
|
|
||||||
|
def test_find_matches_plain(self):
|
||||||
|
lines = ['needle at start', 'Needle again', 'nothing', 'a needle here']
|
||||||
|
matches = find_matches(lines, parse_query('needle'))
|
||||||
|
self.ae([(m.line, m.start, m.end) for m in matches], [(0, 0, 6), (1, 0, 6), (3, 2, 8)])
|
||||||
|
|
||||||
|
matches = find_matches(lines, parse_query('\\c Needle'))
|
||||||
|
self.ae([(m.line, m.start, m.end) for m in matches], [(1, 0, 6)])
|
||||||
|
|
||||||
|
# Regex metacharacters are literal in a plain query
|
||||||
|
self.ae(find_matches(['a+b', 'aab'], parse_query('a+b')), [Match(0, 0, 3)])
|
||||||
|
|
||||||
|
def test_find_matches_regex(self):
|
||||||
|
matches = find_matches(['abc abc', 'nothing here'], parse_query('\\r a.c'))
|
||||||
|
self.ae([(m.line, m.start, m.end) for m in matches], [(0, 0, 3), (0, 4, 7)])
|
||||||
|
|
||||||
|
# Empty matches are skipped and do not loop forever
|
||||||
|
self.ae(find_matches(['abc'], parse_query('\\r x*')), [])
|
||||||
|
|
||||||
|
def test_current_match(self):
|
||||||
|
lines = ['one 17 here', 'nothing', '17 and 17']
|
||||||
|
query = parse_query('17')
|
||||||
|
matches = find_matches(lines, query)
|
||||||
|
search = ScrollbackSearch(query, compile_query(query), matches, total_lines=len(lines))
|
||||||
|
self.ae(len(search), 3)
|
||||||
|
self.ae(search.current_match, Match(0, 4, 6))
|
||||||
|
search.index = 2
|
||||||
|
self.ae(search.current_match, Match(2, 7, 9))
|
||||||
|
|
||||||
|
# The current match is the only one with its own color, and navigation
|
||||||
|
# moves that color along
|
||||||
|
spans = search.marker_spans(lines)
|
||||||
|
self.ae(spans['one 17 here'], ((4, 6, MATCH_COLOR),))
|
||||||
|
self.ae(spans['17 and 17'], ((0, 2, MATCH_COLOR), (7, 9, CURRENT_MATCH_COLOR)))
|
||||||
|
search.index = 1
|
||||||
|
self.ae(search.marker_spans(lines)['17 and 17'], ((0, 2, CURRENT_MATCH_COLOR), (7, 9, MATCH_COLOR)))
|
||||||
|
|
||||||
|
# Wrapping the index keeps exactly one current match selected
|
||||||
|
search.index = 4 % len(search.matches)
|
||||||
|
self.ae(sum(1 for found in search.marker_spans(lines).values() for span in found if span[2] == CURRENT_MATCH_COLOR), 1)
|
||||||
|
|
||||||
|
def test_scroll_offset(self):
|
||||||
|
self.ae(scroll_offset_for(Match(0, 0, 1), 100, 10), 90)
|
||||||
|
self.ae(scroll_offset_for(Match(50, 0, 1), 100, 10), 43)
|
||||||
|
self.ae(scroll_offset_for(Match(99, 0, 1), 100, 10), 0)
|
||||||
|
# No scrollback: the visible screen is always shown as is
|
||||||
|
self.ae(scroll_offset_for(Match(3, 0, 1), 5, 5), 0)
|
||||||
|
|
||||||
|
def test_performance_on_large_scrollback(self):
|
||||||
|
lines = [f'line {i} with some ordinary text' for i in range(10_000)]
|
||||||
|
for i in range(0, 10_000, 10):
|
||||||
|
lines[i] = 'needle ' + lines[i]
|
||||||
|
query = parse_query('needle')
|
||||||
|
start = time.monotonic()
|
||||||
|
matches = find_matches(lines, query)
|
||||||
|
elapsed = time.monotonic() - start
|
||||||
|
self.ae(len(matches), 1000)
|
||||||
|
self.assertLess(elapsed, 0.05, f'searching 10 000 lines took {elapsed * 1000:.1f} ms')
|
||||||
+6
-1
@@ -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.6
|
pkgver=0.1.11
|
||||||
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
@@ -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.6-2` remplace le `0.1.6-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
@@ -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.6"), "by", formatter.Title("BlackAngelTV"))
|
fmt.Sprintln(formatter.Italic("fws-kitty"), formatter.Opt("0.1.11"), "by", formatter.Title("BlackAngelTV"))
|
||||||
}
|
}
|
||||||
|
|
||||||
func (self *Command) ShowVersion() {
|
func (self *Command) ShowVersion() {
|
||||||
|
|||||||
Reference in new issue
Block a user