Compare commits
6
Commits
v0.1.6
..
de13151af1
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
de13151af1
|
||
|
|
fab02aa915
|
||
|
|
f324f5fff2
|
||
|
|
bcf3fdff7b
|
||
|
|
90e6355841 | ||
|
|
ea29472b27 |
No files matched your search
@@ -10,7 +10,6 @@
|
|||||||
*_generated.h
|
*_generated.h
|
||||||
*.local.md
|
*.local.md
|
||||||
/dependencies
|
/dependencies
|
||||||
/.venv
|
|
||||||
/tags
|
/tags
|
||||||
/build/
|
/build/
|
||||||
/fonts/
|
/fonts/
|
||||||
@@ -32,7 +31,6 @@ __pycache__/
|
|||||||
bypy/b
|
bypy/b
|
||||||
bypy/virtual-machines.conf
|
bypy/virtual-machines.conf
|
||||||
_codeql_detected_source_root
|
_codeql_detected_source_root
|
||||||
/.tools/
|
|
||||||
|
|
||||||
# --- Local tool state and caches (never committed) ---
|
# --- Local tool state and caches (never committed) ---
|
||||||
.freebuff/
|
.freebuff/
|
||||||
|
|||||||
@@ -1,393 +0,0 @@
|
|||||||
# Raccourcis clavier de FWS-Kitty
|
|
||||||
|
|
||||||
Tous les raccourcis de ce document sont **actifs par défaut** : kitty et les
|
|
||||||
fonctions ajoutées par FWS s'utilisent au lancement sans écrire une seule ligne
|
|
||||||
de configuration. Le fichier couvre les raccourcis globaux du terminal, ceux des
|
|
||||||
fonctions FWS (gestionnaire de fichiers, historique du presse-papiers,
|
|
||||||
restauration de session) et les touches des interfaces intégrées (kittens).
|
|
||||||
|
|
||||||
Les tableaux reflètent les valeurs de `kitty/options/definition.py`. La palette
|
|
||||||
de commandes (`Ctrl+Shift+F3`) liste en direct toutes les actions, leur touche
|
|
||||||
et leur catégorie, y compris les actions sans raccourci.
|
|
||||||
|
|
||||||
> **Aide rapide** : `Ctrl+Shift+H` (`kitty_mod+H`) ouvre le panneau latéral qui
|
|
||||||
> liste tous les raccourcis, avec recherche et catégories. Dans le shell kitty,
|
|
||||||
> `help` fait la même chose.
|
|
||||||
|
|
||||||
## Conventions
|
|
||||||
|
|
||||||
| Notation | Signification |
|
|
||||||
| --- | --- |
|
|
||||||
| `kitty_mod` | Alias de `Ctrl+Shift` sous Linux, BSD et macOS, redéfinissable avec l'option `kitty_mod`. |
|
|
||||||
| `Ctrl+Shift+X` | Maintenir `Ctrl` et `Shift`, puis appuyer sur `X`. |
|
|
||||||
| `Ctrl+Shift+P` puis `F` | Séquence : relâcher la première combinaison avant de presser `F`. |
|
|
||||||
| `→`, `←`, `↑`, `↓` | Flèches de direction. |
|
|
||||||
| `Entrée`, `Échap`, `Retour arrière`, `Suppr` | Touches `Enter`, `Escape`, `Backspace`, `Delete`. |
|
|
||||||
| `Page↑`, `Page↓`, `Début`, `Fin` | Touches `Page Up`, `Page Down`, `Home`, `End`. |
|
|
||||||
| `KP+`, `KP-` | Touches `+` et `-` du pavé numérique. |
|
|
||||||
|
|
||||||
`kitty_mod` vaut `Ctrl+Shift` sur toutes les plateformes : `kitty_mod+c` se lit
|
|
||||||
`Ctrl+Shift+C`, même sous macOS. Les raccourcis macOS habituels (`Cmd+C`,
|
|
||||||
`Cmd+V`, `Cmd+T`…) sont des mappings distincts, regroupés plus bas.
|
|
||||||
|
|
||||||
## Fonctions ajoutées par FWS
|
|
||||||
|
|
||||||
| Touche | Action |
|
|
||||||
| --- | --- |
|
|
||||||
| `Ctrl+Shift+E` | Ouvre le gestionnaire de fichiers dans un dock à gauche de la fenêtre. La touche est la même sous macOS. |
|
|
||||||
| `Ctrl+Shift+Alt+V` (`kitty_mod+alt+v`) | Colle une entrée de l'historique du presse-papiers. |
|
|
||||||
| `Ctrl+Shift+Alt+F` (`kitty_mod+alt+f`) | Demande une recherche floue, puis colle l'entrée choisie. |
|
|
||||||
| `Ctrl+Shift+Alt+R` (`kitty_mod+alt+r`) | Restaure la session enregistrée à la dernière fermeture de kitty. |
|
|
||||||
| `Ctrl+Shift+H` (`kitty_mod+H`) | Ouvre le panneau latéral de tous les raccourcis. |
|
|
||||||
|
|
||||||
Deux fonctions FWS ne demandent aucune touche :
|
|
||||||
|
|
||||||
- Les **notifications de fin de commande** sont actives avec
|
|
||||||
`notify_on_cmd_finish unfocused` : une commande de plus de 5 secondes notifie
|
|
||||||
quand la fenêtre n'est plus au premier plan, avec sa durée et son code de
|
|
||||||
sortie.
|
|
||||||
- La **barre d'onglets** affiche le code de sortie des commandes en échec
|
|
||||||
(`✘ code`), le répertoire courant abrégé et les boutons `×` (fermer l'onglet)
|
|
||||||
et `+` (nouvel onglet). Elle est visible dès le premier onglet.
|
|
||||||
|
|
||||||
> `Ctrl+Shift+E` ouvrait auparavant les URLs visibles (`open_url`). Le
|
|
||||||
> gestionnaire de fichiers prend la touche par défaut. Pour retrouver l'ancien
|
|
||||||
> comportement, ajoutez `map ctrl+shift+e open_url_with_hints` dans
|
|
||||||
> `kitty.conf` ; le panneau reste accessible avec `kitten file-manager`.
|
|
||||||
|
|
||||||
## Presse-papiers
|
|
||||||
|
|
||||||
| Touche | Action |
|
|
||||||
| --- | --- |
|
|
||||||
| `Ctrl+Shift+C` | Copie la sélection dans le presse-papiers. |
|
|
||||||
| `Ctrl+Shift+V` | Colle le presse-papiers. |
|
|
||||||
| `Ctrl+Shift+S` | Colle la sélection primaire. |
|
|
||||||
| `Maj+Inser` | Colle la sélection primaire. |
|
|
||||||
| `Ctrl+Shift+Alt+V` | Colle une entrée de l'historique. |
|
|
||||||
| `Ctrl+Shift+Alt+F` | Recherche dans l'historique puis colle. |
|
|
||||||
| `Ctrl+Shift+O` | Passe la sélection à un programme (navigateur par défaut sans argument). |
|
|
||||||
|
|
||||||
## Défilement et historique
|
|
||||||
|
|
||||||
| Touche | Action |
|
|
||||||
| --- | --- |
|
|
||||||
| `Ctrl+Shift+↑` ou `Ctrl+Shift+K` | Défile d'une ligne vers le haut. |
|
|
||||||
| `Ctrl+Shift+↓` ou `Ctrl+Shift+J` | Défile d'une ligne vers le bas. |
|
|
||||||
| `Ctrl+Shift+Page↑` | Défile d'une page vers le haut. |
|
|
||||||
| `Ctrl+Shift+Page↓` | Défile d'une page vers le bas. |
|
|
||||||
| `Ctrl+Shift+Début` | Va au début de l'historique. |
|
|
||||||
| `Ctrl+Shift+Fin` | Va à la fin de l'historique. |
|
|
||||||
| `Ctrl+Shift+Z` | Va au prompt précédent. |
|
|
||||||
| `Ctrl+Shift+X` | Va au prompt suivant. |
|
|
||||||
| `Ctrl+Shift+H` | Affiche tout l'historique dans un pager. |
|
|
||||||
| `Ctrl+Shift+G` | Affiche la sortie de la dernière commande dans un pager. |
|
|
||||||
| `Ctrl+Shift+/` | Recherche dans l'historique. |
|
|
||||||
|
|
||||||
## Fenêtres
|
|
||||||
|
|
||||||
| Touche | Action |
|
|
||||||
| --- | --- |
|
|
||||||
| `Ctrl+Shift+Entrée` | Nouvelle fenêtre dans l'onglet courant. |
|
|
||||||
| `Ctrl+Shift+N` | Nouvelle fenêtre du système (OS Window). |
|
|
||||||
| `Ctrl+Shift+W` | Ferme la fenêtre courante. |
|
|
||||||
| `Ctrl+Shift+]` | Fenêtre suivante. |
|
|
||||||
| `Ctrl+Shift+[` | Fenêtre précédente. |
|
|
||||||
| `Ctrl+Shift+F` | Avance la fenêtre dans la disposition. |
|
|
||||||
| `Ctrl+Shift+B` | Recule la fenêtre dans la disposition. |
|
|
||||||
| ``Ctrl+Shift+` `` | Place la fenêtre au premier plan de la disposition. |
|
|
||||||
| `Ctrl+Shift+R` | Démarre le redimensionnement au clavier. |
|
|
||||||
| `Ctrl+Shift+1` … `Ctrl+Shift+0` | Active la 1re … 10e fenêtre. |
|
|
||||||
| `Ctrl+Shift+F7` | Active la fenêtre visible sous le pointeur. |
|
|
||||||
| `Ctrl+Shift+F8` | Échange la fenêtre courante avec celle sous le pointeur. |
|
|
||||||
|
|
||||||
## Onglets
|
|
||||||
|
|
||||||
| Touche | Action |
|
|
||||||
| --- | --- |
|
|
||||||
| `Ctrl+Shift+→` | Onglet suivant. |
|
|
||||||
| `Ctrl+Shift+←` | Onglet précédent. |
|
|
||||||
| `Ctrl+Tab` / `Ctrl+Shift+Tab` | Onglet suivant / précédent. |
|
|
||||||
| `Ctrl+Shift+T` | Nouvel onglet. |
|
|
||||||
| `Ctrl+Shift+Q` | Ferme l'onglet courant. |
|
|
||||||
| `Ctrl+Shift+.` | Déplace l'onglet vers la droite. |
|
|
||||||
| `Ctrl+Shift+,` | Déplace l'onglet vers la gauche. |
|
|
||||||
| `Ctrl+Shift+Alt+T` | Renomme l'onglet courant. |
|
|
||||||
| `Ctrl+Shift+F11` | Bascule le plein écran. |
|
|
||||||
| `Ctrl+Shift+F10` | Bascule la maximisation. |
|
|
||||||
|
|
||||||
## Dispositions
|
|
||||||
|
|
||||||
| Touche | Action |
|
|
||||||
| --- | --- |
|
|
||||||
| `Ctrl+Shift+L` | Passe à la disposition suivante. |
|
|
||||||
|
|
||||||
## Taille de police
|
|
||||||
|
|
||||||
| Touche | Action |
|
|
||||||
| --- | --- |
|
|
||||||
| `Ctrl+Shift+=`, `Ctrl+Shift++` ou `Ctrl+Shift+KP+` | Agrandit la police de 2 points. |
|
|
||||||
| `Ctrl+Shift+-` ou `Ctrl+Shift+KP-` | Réduit la police de 2 points. |
|
|
||||||
| `Ctrl+Shift+Retour arrière` | Rétablit la taille configurée. |
|
|
||||||
|
|
||||||
## Sélectionner du texte (hints)
|
|
||||||
|
|
||||||
| Touche | Action |
|
|
||||||
| --- | --- |
|
|
||||||
| `Ctrl+Shift+P` puis `F` | Insère le chemin sélectionné dans la ligne de commande. |
|
|
||||||
| `Ctrl+Shift+P` puis `Maj+F` | Ouvre le chemin sélectionné. |
|
|
||||||
| `Ctrl+Shift+P` puis `C` | Choisit un fichier et l'insère. |
|
|
||||||
| `Ctrl+Shift+P` puis `D` | Choisit un répertoire et l'insère. |
|
|
||||||
| `Ctrl+Shift+P` puis `L` | Insère la ligne sélectionnée. |
|
|
||||||
| `Ctrl+Shift+P` puis `W` | Insère le mot sélectionné. |
|
|
||||||
| `Ctrl+Shift+P` puis `H` | Insère le hash (commit git) sélectionné. |
|
|
||||||
| `Ctrl+Shift+P` puis `N` | Ouvre le fichier à la ligne indiquée (`fichier:42`). |
|
|
||||||
| `Ctrl+Shift+P` puis `Y` | Ouvre le lien hypertexte sélectionné. |
|
|
||||||
|
|
||||||
Dans une sélection par hints, tapez l'étiquette affichée sur le texte visé ;
|
|
||||||
`Entrée` ou `Espace` valide une étiquette vide lorsque les hints utilisent
|
|
||||||
plusieurs lettres.
|
|
||||||
|
|
||||||
## Sessions
|
|
||||||
|
|
||||||
| Touche | Action |
|
|
||||||
| --- | --- |
|
|
||||||
| `Ctrl+Shift+Alt+R` | Restaure les onglets, dispositions, répertoires et titres de la dernière session. |
|
|
||||||
|
|
||||||
La même restauration est disponible au démarrage :
|
|
||||||
|
|
||||||
```sh
|
|
||||||
kitty --session=last
|
|
||||||
```
|
|
||||||
|
|
||||||
`save_as_session`, `goto_session` et `close_session` n'ont pas de touche par
|
|
||||||
défaut : lancez-les depuis la palette de commandes (`Ctrl+Shift+F3`) ou
|
|
||||||
associez-les dans `kitty.conf`.
|
|
||||||
|
|
||||||
## Divers
|
|
||||||
|
|
||||||
| Touche | Action |
|
|
||||||
| --- | --- |
|
|
||||||
| `Ctrl+Shift+F1` | Ouvre la documentation de kitty. |
|
|
||||||
| `Ctrl+Shift+F3` | Ouvre la palette de commandes. |
|
|
||||||
| `Ctrl+Shift+E` | Ouvre le gestionnaire de fichiers (FWS). |
|
|
||||||
| `Ctrl+Shift+F2` | Ouvre `kitty.conf` dans l'éditeur. |
|
|
||||||
| `Ctrl+Shift+F5` | Recharge la configuration. |
|
|
||||||
| `Ctrl+Shift+F6` | Affiche la configuration effective. |
|
|
||||||
| `Ctrl+Shift+U` | Saisie de caractères Unicode. |
|
|
||||||
| `Ctrl+Shift+Échap` | Ouvre un shell kitty (contrôle à distance). |
|
|
||||||
| `Ctrl+Shift+A` puis `M` | Augmente l'opacité du fond. |
|
|
||||||
| `Ctrl+Shift+A` puis `L` | Diminue l'opacité du fond. |
|
|
||||||
| `Ctrl+Shift+A` puis `1` | Fond totalement opaque. |
|
|
||||||
| `Ctrl+Shift+A` puis `D` | Rétablit l'opacité configurée. |
|
|
||||||
| `Ctrl+Shift+Suppr` | Réinitialise le terminal. |
|
|
||||||
| `Ctrl+Shift+Alt+H` | Envoie `Hello World` au terminal (exemple fourni par kitty). |
|
|
||||||
|
|
||||||
## Raccourcis macOS
|
|
||||||
|
|
||||||
Sous macOS, les raccourcis par défaut de kitty sont majoritairement en `Cmd`,
|
|
||||||
tandis que les raccourcis FWS basés sur `kitty_mod` restent en `Ctrl+Shift`.
|
|
||||||
Les entrées suivantes complètent les tableaux précédents.
|
|
||||||
|
|
||||||
| Touche | Action |
|
|
||||||
| --- | --- |
|
|
||||||
| `Cmd+C` | Copie, ou transmet `Ctrl+C` au programme s'il n'y a pas de sélection. |
|
|
||||||
| `Cmd+V` | Colle le presse-papiers. |
|
|
||||||
| `Cmd+↑` / `Cmd+↓` | Défile d'une ligne vers le haut / le bas. |
|
|
||||||
| `Cmd+Page↑` / `Cmd+Page↓` | Défile d'une page vers le haut / le bas. |
|
|
||||||
| `Cmd+Début` / `Cmd+Fin` | Début / fin de l'historique. |
|
|
||||||
| `Cmd+F` | Recherche dans l'historique. |
|
|
||||||
| `Cmd+Entrée` | Nouvelle fenêtre. |
|
|
||||||
| `Cmd+N` | Nouvelle fenêtre du système. |
|
|
||||||
| `Cmd+W` | Ferme l'onglet ; `Cmd+Shift+W` ferme la fenêtre du système. |
|
|
||||||
| `Cmd+T` | Nouvel onglet. |
|
|
||||||
| `Cmd+Shift+]` / `Cmd+Shift+[` | Onglet suivant / précédent. |
|
|
||||||
| `Cmd+Shift+I` | Renomme l'onglet. |
|
|
||||||
| `Cmd+1` … `Cmd+9` | Active la 1re … 9e fenêtre. |
|
|
||||||
| `Cmd+R` | Redimensionnement au clavier. |
|
|
||||||
| ``Cmd+` `` / ``Cmd+Shift+` `` | Fenêtre du système suivante / précédente. |
|
|
||||||
| `Cmd++`, `Cmd+=`, `Cmd+Shift+=` | Agrandit la police. |
|
|
||||||
| `Cmd+-`, `Cmd+Shift+-` | Réduit la police. |
|
|
||||||
| `Cmd+0` | Rétablit la taille de police. |
|
|
||||||
| `Cmd+,` | Ouvre `kitty.conf`. |
|
|
||||||
| `Ctrl+Cmd+,` | Recharge la configuration. |
|
|
||||||
| `Alt+Cmd+,` | Affiche la configuration effective. |
|
|
||||||
| `Alt+Cmd+R` | Réinitialise le terminal. |
|
|
||||||
| `Ctrl+Cmd+F` | Bascule le plein écran. |
|
|
||||||
| `Ctrl+Cmd+Espace` | Saisie Unicode. |
|
|
||||||
| `Cmd+K` | Efface l'écran jusqu'au curseur. |
|
|
||||||
| `Alt+Cmd+K` | Efface l'historique. |
|
|
||||||
| `Cmd+L` | Efface la dernière commande. |
|
|
||||||
| `Ctrl+Cmd+L` | Efface l'écran et l'historique. |
|
|
||||||
| `Alt+Cmd+S` | Active la saisie clavier sécurisée. |
|
|
||||||
| `Cmd+Shift+/` | Ouvre le site de kitty. |
|
|
||||||
| `Cmd+H` / `Alt+Cmd+H` | Masque kitty / les autres applications. |
|
|
||||||
| `Cmd+M` | Réduit la fenêtre. |
|
|
||||||
| `Cmd+Q` | Quitte kitty. |
|
|
||||||
|
|
||||||
## Barre d'onglets et souris
|
|
||||||
|
|
||||||
| Geste | Action |
|
|
||||||
| --- | --- |
|
|
||||||
| Clic gauche sur un onglet | Active l'onglet. |
|
|
||||||
| Clic sur `×` | Ferme l'onglet. |
|
|
||||||
| Clic sur `+` | Ouvre un nouvel onglet. |
|
|
||||||
| Clic du milieu sur un onglet | Ferme l'onglet. |
|
|
||||||
| Glisser un onglet | Réordonne, détache ou déplace l'onglet. |
|
|
||||||
| Clic gauche dans le gestionnaire de fichiers | Sélectionne l'entrée. |
|
|
||||||
|
|
||||||
## Gestionnaire de fichiers (`Ctrl+Shift+E`)
|
|
||||||
|
|
||||||
| Touche | Action |
|
|
||||||
| --- | --- |
|
|
||||||
| `Entrée` | Entre dans le répertoire sélectionné, ou ouvre le fichier dans l'éditeur dans un nouvel onglet. |
|
|
||||||
| `→` ou `L` | Entre dans le répertoire sélectionné sans toucher au shell. |
|
|
||||||
| `←`, `Retour arrière` ou `H` | Remonte au répertoire parent. |
|
|
||||||
| `Ctrl+Entrée` ou `C` | Déplace le shell vers le répertoire affiché puis ferme le panneau. |
|
|
||||||
| `↑` ou `K` | Sélection précédente. |
|
|
||||||
| `↓` ou `J` | Sélection suivante. |
|
|
||||||
| `Tab` / `Maj+Tab` | Sélection suivante / précédente. |
|
|
||||||
| `Page↑` ou `Ctrl+B` | Sélection précédente d'une page. |
|
|
||||||
| `Page↓` ou `Ctrl+F` | Sélection suivante d'une page. |
|
|
||||||
| `Début` ou `G` | Première entrée. |
|
|
||||||
| `Fin` ou `Maj+G` | Dernière entrée. |
|
|
||||||
| `/` | Filtre la liste par recherche floue ; `Entrée` ouvre la sélection, `Échap` efface la requête. |
|
|
||||||
| `:` | Ouvre la palette des actions du panneau ; `Entrée` exécute l'action. |
|
|
||||||
| `O` | Ouvre le fichier sélectionné dans un nouvel onglet. |
|
|
||||||
| `T` | Ouvre le fichier sélectionné dans une nouvelle fenêtre du système. |
|
|
||||||
| `N` | Crée un fichier. |
|
|
||||||
| `Maj+N` ou `A` | Crée un répertoire. |
|
|
||||||
| `R` | Renomme l'entrée sélectionnée. |
|
|
||||||
| `D` | Supprime l'entrée après confirmation par `Y` (jamais récursivement). |
|
|
||||||
| `Y` | Copie le chemin dans le presse-papiers. |
|
|
||||||
| `.` | Affiche ou masque les entrées cachées. |
|
|
||||||
| `Ctrl+R` | Recharge le répertoire. |
|
|
||||||
| `Échap` ou `Q` | Ferme le panneau sans changer de répertoire. |
|
|
||||||
|
|
||||||
Toutes ces touches se redéfinissent dans `~/.config/kitty/file-manager.conf`
|
|
||||||
avec la syntaxe `map <touche> <action>`.
|
|
||||||
|
|
||||||
## Palette de commandes (`Ctrl+Shift+F3`)
|
|
||||||
|
|
||||||
| Touche | Action |
|
|
||||||
| --- | --- |
|
|
||||||
| Texte | Filtre les résultats. |
|
|
||||||
| `Entrée` | Exécute l'action sélectionnée. |
|
|
||||||
| `Échap` | Efface la requête, ou ferme la palette si elle est vide. |
|
|
||||||
| `↑`, `Maj+Tab`, `Ctrl+K` ou `Ctrl+P` | Sélection précédente. |
|
|
||||||
| `↓`, `Tab`, `Ctrl+J` ou `Ctrl+N` | Sélection suivante. |
|
|
||||||
| `Page↑` / `Page↓` | Sélection précédente / suivante d'une page. |
|
|
||||||
| `Début` / `Fin` | Premier / dernier résultat. |
|
|
||||||
| `Retour arrière` | Efface le dernier caractère de la requête. |
|
|
||||||
| `F12` | Affiche ou masque les actions sans raccourci. |
|
|
||||||
|
|
||||||
## Panneau d'aide (`help`)
|
|
||||||
|
|
||||||
Dans le shell kitty (`Ctrl+Shift+Échap`), `help` sans argument ouvre un panneau
|
|
||||||
latéral qui liste tous les raccourcis actifs, classés par catégorie, avec une
|
|
||||||
recherche rapide. Depuis un terminal : `kitty +kitten help` ; le raccourci
|
|
||||||
par défaut `Ctrl+Shift+H` (`kitty_mod+H`) ouvre le même panneau.
|
|
||||||
|
|
||||||
| Touche | Action |
|
|
||||||
| --- | --- |
|
|
||||||
| Texte | Filtre les raccourcis. |
|
|
||||||
| `Échap` | Efface la requête, puis ferme le panneau. |
|
|
||||||
| `↑` / `↓`, `Ctrl+K` / `Ctrl+J` | Raccourci précédent / suivant. |
|
|
||||||
| `Tab` / `Maj+Tab` | Raccourci suivant / précédent. |
|
|
||||||
| `Page↑` / `Page↓` | Défile d'une page. |
|
|
||||||
| `Début` / `Fin` | Premier / dernier raccourci. |
|
|
||||||
| `F12` | Affiche ou masque les actions sans raccourci. |
|
|
||||||
| `Entrée` | Sans effet : le panneau est en lecture seule. |
|
|
||||||
|
|
||||||
## Historique du presse-papiers (`Ctrl+Shift+Alt+V`)
|
|
||||||
|
|
||||||
| Touche | Action |
|
|
||||||
| --- | --- |
|
|
||||||
| Numéro affiché devant une entrée | Colle immédiatement cette entrée. |
|
|
||||||
| `Échap` | Ferme la liste sans rien coller. |
|
|
||||||
|
|
||||||
`Ctrl+Shift+Alt+F` commence par demander une requête floue, puis affiche la
|
|
||||||
même liste. L'historique vit en mémoire uniquement : il disparaît à la
|
|
||||||
fermeture de kitty et les copies marquées privées n'y sont jamais enregistrées.
|
|
||||||
|
|
||||||
## Saisie Unicode (`Ctrl+Shift+U`)
|
|
||||||
|
|
||||||
| Touche | Action |
|
|
||||||
| --- | --- |
|
|
||||||
| `F1` … `F4` ou `Ctrl+1` … `Ctrl+4` | Change de mode. |
|
|
||||||
| `Ctrl+[` / `Ctrl+]` ou `Ctrl+Tab` / `Ctrl+Shift+Tab` | Change de mode. |
|
|
||||||
| `Entrée` | Insère le caractère dont le code hexadécimal est saisi. |
|
|
||||||
| `↑` / `↓` | Caractère récent précédent / suivant. |
|
|
||||||
| `.` puis index à deux chiffres | Choisit un caractère récent. |
|
|
||||||
| Flèches ou `Tab` | Sélectionne un caractère parmi les correspondances du mode Nom. |
|
|
||||||
| `Espace` puis `.` et l'index | Sélectionne une correspondance sans les flèches. |
|
|
||||||
|
|
||||||
## Hints
|
|
||||||
|
|
||||||
| Touche | Action |
|
|
||||||
| --- | --- |
|
|
||||||
| Étiquette affichée | Sélectionne le texte marqué. |
|
|
||||||
| `Entrée` ou `Espace` | Valide une étiquette vide quand plusieurs lettres sont nécessaires. |
|
|
||||||
| Clic sur le texte marqué | Sélectionne sans taper l'étiquette. |
|
|
||||||
|
|
||||||
## Diff (`kitten diff`)
|
|
||||||
|
|
||||||
| Touche | Action |
|
|
||||||
| --- | --- |
|
|
||||||
| `Q` | Quitte. |
|
|
||||||
| `K` / `↑`, `J` / `↓` | Défile d'une ligne. |
|
|
||||||
| `Page↑` / `Page↓` | Défile d'une page. |
|
|
||||||
| `Début` / `Fin` | Haut / bas du fichier. |
|
|
||||||
| `Espace` ou `Ctrl+F`, `Ctrl+B` | Page suivante / précédente. |
|
|
||||||
| `Ctrl+D` / `Ctrl+U` | Demi-page vers le bas / le haut. |
|
|
||||||
| `N` / `P` | Modification suivante / précédente. |
|
|
||||||
| `+` / `-` | Augmente / réduit le contexte. |
|
|
||||||
| `A` | Affiche toutes les lignes de contexte. |
|
|
||||||
| `=` | Rétablit le contexte par défaut. |
|
|
||||||
| `/` / `?` | Recherche vers l'avant / l'arrière. |
|
|
||||||
| `Échap` | Efface la recherche ou quitte. |
|
|
||||||
| `>` ou `.`, `<` ou `,` | Correspondance suivante / précédente. |
|
|
||||||
| `Y` | Copie la sélection. |
|
|
||||||
| `Ctrl+C` | Copie la sélection ou quitte. |
|
|
||||||
|
|
||||||
## Choix de fichiers (`kitten choose-files`)
|
|
||||||
|
|
||||||
| Touche | Action |
|
|
||||||
| --- | --- |
|
|
||||||
| Texte | Filtre la liste. |
|
|
||||||
| `Entrée` | Choisit le fichier sélectionné. |
|
|
||||||
| `Tab` | Entre dans le répertoire sélectionné. |
|
|
||||||
| `Maj+Tab` | Remonte d'un répertoire. |
|
|
||||||
| `Ctrl+Entrée` | Choisit le répertoire courant (ou saisit un nom de fichier en mode sauvegarde). |
|
|
||||||
| `Alt+Entrée` | Modifie le nom du fichier sélectionné. |
|
|
||||||
| `Maj+Entrée` | Ajoute ou retire le fichier de la sélection multiple. |
|
|
||||||
| `Ctrl+clic` / `Alt+clic` | Ajoute un fichier / sélectionne une plage à la souris. |
|
|
||||||
|
|
||||||
Les raccourcis de cette interface se redéfinissent dans
|
|
||||||
`~/.config/kitty/choose-files.conf`.
|
|
||||||
|
|
||||||
## Thèmes et polices
|
|
||||||
|
|
||||||
`kitten themes` et `kitten choose-fonts` se pilotent au clavier : tapez quelques
|
|
||||||
lettres pour filtrer, `Entrée` valide la famille ou le thème, `R` affine la
|
|
||||||
police régulière dans `choose-fonts`. Le détail figure dans leurs pages de
|
|
||||||
documentation.
|
|
||||||
|
|
||||||
## Personnaliser un raccourci
|
|
||||||
|
|
||||||
Les raccourcis globaux se redéfinissent dans `~/.config/kitty/kitty.conf` :
|
|
||||||
|
|
||||||
```conf
|
|
||||||
# Remplacer l'ouverture du gestionnaire de fichiers
|
|
||||||
map ctrl+shift+e launch --type=overlay kitten file-manager
|
|
||||||
|
|
||||||
# Rétablir l'ouverture des URLs sur Ctrl+Shift+E
|
|
||||||
map ctrl+shift+e open_url_with_hints
|
|
||||||
|
|
||||||
# Choisir d'autres touches pour l'historique
|
|
||||||
map kitty_mod+alt+h paste_from_clipboard_history
|
|
||||||
map kitty_mod+alt+g search_clipboard_history
|
|
||||||
```
|
|
||||||
|
|
||||||
La configuration est rechargée automatiquement, ou manuellement avec
|
|
||||||
`Ctrl+Shift+F5`. Une touche peut aussi être retirée en la mappant sur rien :
|
|
||||||
`map ctrl+shift+e`.
|
|
||||||
@@ -9,8 +9,7 @@ supprime des entrées, et ouvre les fichiers dans l'éditeur.
|
|||||||
Ce document décrit tout le cycle de vie du projet : récupérer le code, compiler,
|
Ce document décrit tout le cycle de vie du projet : récupérer le code, compiler,
|
||||||
lancer, utiliser l'explorateur, tester, construire le paquet Arch et dépanner.
|
lancer, utiliser l'explorateur, tester, construire le paquet Arch et dépanner.
|
||||||
`DEV.md` reste le guide de développement condensé, `README.asciidoc` est le
|
`DEV.md` reste le guide de développement condensé, `README.asciidoc` est le
|
||||||
README d'origine de kitty et `RACCOURCIS-CLAVIER.md` liste tous les raccourcis
|
README d'origine de kitty.
|
||||||
actifs par défaut, sans configuration.
|
|
||||||
|
|
||||||
## Contenu de la branche `feat/file-manager-panel`
|
## Contenu de la branche `feat/file-manager-panel`
|
||||||
|
|
||||||
@@ -162,12 +161,11 @@ kitten file-manager ~/Projets # répertoire de départ
|
|||||||
kitten file-manager --show-hidden
|
kitten file-manager --show-hidden
|
||||||
```
|
```
|
||||||
|
|
||||||
`Ctrl+Shift+E` ouvre le panneau par défaut, dans un dock latéral gauche. Pour
|
Raccourci pour l'avoir en permanence dans un dock latéral, à ajouter dans
|
||||||
remplacer ce comportement, redéfinissez le raccourci dans
|
|
||||||
`~/.config/kitty/kitty.conf` :
|
`~/.config/kitty/kitty.conf` :
|
||||||
|
|
||||||
```conf
|
```conf
|
||||||
map ctrl+shift+e launch --type=overlay kitten file-manager
|
map ctrl+shift+e launch --type=window-dock --dock-edge=left --dock-size=60 kitten file-manager
|
||||||
```
|
```
|
||||||
|
|
||||||
Un fichier validé s'ouvre dans un nouvel onglet, donc en pleine fenêtre même
|
Un fichier validé s'ouvre dans un nouvel onglet, donc en pleine fenêtre même
|
||||||
@@ -183,10 +181,6 @@ shell : `Ctrl+Entrée` dans un dock ne peut donc pas faire de `cd`.
|
|||||||
| `→` / `L` | Entre dans le répertoire sélectionné sans toucher au shell |
|
| `→` / `L` | Entre dans le répertoire sélectionné sans toucher au shell |
|
||||||
| `←` / `Retour arrière` / `H` | Remonte au répertoire parent |
|
| `←` / `Retour arrière` / `H` | Remonte au répertoire parent |
|
||||||
| `Ctrl+Entrée` / `C` | Déplace le shell vers le répertoire affiché, sans tenir compte de la sélection |
|
| `Ctrl+Entrée` / `C` | Déplace le shell vers le répertoire affiché, sans tenir compte de la sélection |
|
||||||
| `/` | Filtre la liste par recherche floue ; `Entrée` ouvre la sélection, `Échap` efface la requête |
|
|
||||||
| `:` | Ouvre la palette des actions, filtrable, `Entrée` exécute l'action |
|
|
||||||
| `O` / `T` | Ouvre le fichier sélectionné dans un nouvel onglet / une nouvelle fenêtre |
|
|
||||||
| `A` | Alias de `Maj+N` : crée un répertoire |
|
|
||||||
| `↑` / `K`, `↓` / `J` | Déplace la sélection |
|
| `↑` / `K`, `↓` / `J` | Déplace la sélection |
|
||||||
| `Page préc.` / `Ctrl+B`, `Page suiv.` / `Ctrl+F` | Déplace la sélection d'une page |
|
| `Page préc.` / `Ctrl+B`, `Page suiv.` / `Ctrl+F` | Déplace la sélection d'une page |
|
||||||
| `Début` / `G`, `Fin` / `Maj+G` | Première / dernière entrée |
|
| `Début` / `G`, `Fin` / `Maj+G` | Première / dernière entrée |
|
||||||
@@ -223,7 +217,7 @@ Les réglages vivent dans `~/.config/kitty/file-manager.conf` (même syntaxe que
|
|||||||
# Afficher les fichiers cachés à l'ouverture
|
# Afficher les fichiers cachés à l'ouverture
|
||||||
show_hidden yes
|
show_hidden yes
|
||||||
|
|
||||||
# name (défaut), mtime (plus récent d'abord) ou size (plus gros d'abord)
|
# name (défaut) ou mtime (plus récent d'abord)
|
||||||
sort_by mtime
|
sort_by mtime
|
||||||
|
|
||||||
# Remplacer un raccourci
|
# Remplacer un raccourci
|
||||||
|
|||||||
+2
-5
@@ -16,12 +16,9 @@ override OPTS=
|
|||||||
endif
|
endif
|
||||||
|
|
||||||
# You can set these variables from the command line.
|
# You can set these variables from the command line.
|
||||||
# Prefer the tool environment kept at the root of the checkout, so that the
|
|
||||||
# documentation builds without installing its extensions system-wide.
|
|
||||||
VENV ?= ../.venv
|
|
||||||
SPHINXOPTS = -n -q -j auto -T $(FAIL_WARN) $(OPTS)
|
SPHINXOPTS = -n -q -j auto -T $(FAIL_WARN) $(OPTS)
|
||||||
SPHINXBUILD ?= $(if $(wildcard $(VENV)/bin/sphinx-build),$(VENV)/bin/sphinx-build,sphinx-build)
|
SPHINXBUILD = sphinx-build
|
||||||
SPHINXAUTOBUILD ?= $(if $(wildcard $(VENV)/bin/sphinx-autobuild),$(VENV)/bin/sphinx-autobuild,sphinx-autobuild)
|
SPHINXAUTOBUILD = sphinx-autobuild
|
||||||
SPHINXPROJ = kitty
|
SPHINXPROJ = kitty
|
||||||
SOURCEDIR = .
|
SOURCEDIR = .
|
||||||
BUILDDIR = _build
|
BUILDDIR = _build
|
||||||
|
|||||||
@@ -1,127 +0,0 @@
|
|||||||
.. _accessibility:
|
|
||||||
|
|
||||||
Accessibilité
|
|
||||||
=============
|
|
||||||
|
|
||||||
|kitty| se pilote entièrement au clavier et son mode fort contraste garantit un
|
|
||||||
rapport de contraste d'au moins :code:`4.5:1`, le seuil du niveau AA des
|
|
||||||
:link:`WCAG <https://en.wikipedia.org/wiki/Web_Content_Accessibility_Guidelines>`.
|
|
||||||
La navigation fonctionne sans réglage : les raccourcis décrits ici sont ceux par
|
|
||||||
défaut.
|
|
||||||
|
|
||||||
Navigation clavier par défaut
|
|
||||||
-----------------------------
|
|
||||||
|
|
||||||
Tous les kittens interactifs acceptent la tabulation, les flèches, :kbd:`Entrée`
|
|
||||||
et :kbd:`Échap`. Aucune configuration n'est nécessaire : les raccourcis sont
|
|
||||||
livrés avec |kitty| et restent actifs même sans :file:`kitty.conf`.
|
|
||||||
|
|
||||||
.. list-table::
|
|
||||||
:header-rows: 1
|
|
||||||
:widths: auto
|
|
||||||
|
|
||||||
* - Interface
|
|
||||||
- Ouverture par défaut
|
|
||||||
- Navigation
|
|
||||||
* - :doc:`Gestionnaire de fichiers </kittens/file-manager>`
|
|
||||||
- :kbd:`Ctrl+Shift+E`
|
|
||||||
- :kbd:`Tab` / :kbd:`Maj+Tab`, :kbd:`↓` / :kbd:`↑`, :kbd:`Page↓` /
|
|
||||||
:kbd:`Page↑`, :kbd:`Début` / :kbd:`Fin`, :kbd:`Entrée`, :kbd:`Échap`
|
|
||||||
* - :doc:`Palette de commandes </kittens/command-palette>`
|
|
||||||
- :kbd:`Ctrl+Shift+F3`
|
|
||||||
- :kbd:`Tab` / :kbd:`Maj+Tab`, :kbd:`↓` / :kbd:`↑`, :kbd:`Page↓` /
|
|
||||||
:kbd:`Page↑`, :kbd:`Début` / :kbd:`Fin`, :kbd:`Entrée`, :kbd:`Échap`
|
|
||||||
* - :doc:`Saisie Unicode </kittens/unicode_input>`
|
|
||||||
- :kbd:`Ctrl+Shift+U`
|
|
||||||
- :kbd:`Tab` / :kbd:`Maj+Tab` (changement de zone), flèches,
|
|
||||||
:kbd:`Entrée`, :kbd:`Échap`
|
|
||||||
|
|
||||||
Les autres kittens interactifs (:doc:`thèmes </kittens/themes>`,
|
|
||||||
:doc:`choix des polices </kittens/choose-fonts>`, :doc:`diff </kittens/diff>`,
|
|
||||||
:doc:`hints </kittens/hints>`) suivent la même convention : les flèches
|
|
||||||
parcourent les listes, :kbd:`Entrée` valide et :kbd:`Échap` annule. Le détail
|
|
||||||
des touches propres à chaque kitten figure dans sa page de documentation.
|
|
||||||
|
|
||||||
Raccourcis configurables
|
|
||||||
------------------------
|
|
||||||
|
|
||||||
Les raccourcis par défaut ne sont qu'un point de départ. Ils se redéfinissent
|
|
||||||
dans :file:`kitty.conf` pour les actions de |kitty| et dans
|
|
||||||
:file:`file-manager.conf` pour le panneau, sans toucher aux valeurs par défaut
|
|
||||||
du programme. Par exemple, pour remplacer la tabulation par :kbd:`J` / :kbd:`K`
|
|
||||||
dans le panneau :
|
|
||||||
|
|
||||||
.. code-block:: conf
|
|
||||||
|
|
||||||
# ~/.config/kitty/file-manager.conf
|
|
||||||
map move_up k move_up
|
|
||||||
map move_down j move_down
|
|
||||||
|
|
||||||
Le raccourci d'ouverture se change lui aussi :
|
|
||||||
|
|
||||||
.. code-block:: conf
|
|
||||||
|
|
||||||
# ~/.config/kitty/kitty.conf
|
|
||||||
map ctrl+shift+e launch --type=overlay kitten file-manager
|
|
||||||
|
|
||||||
Mode fort contraste
|
|
||||||
-------------------
|
|
||||||
|
|
||||||
|kitty| intègre un mode qui garantit le contraste entre le texte et le fond,
|
|
||||||
sans changer la teinte des couleurs. Il s'active avec
|
|
||||||
:opt:`text_fg_override_threshold` et le seuil de contraste voulu :
|
|
||||||
|
|
||||||
.. code-block:: conf
|
|
||||||
|
|
||||||
text_fg_override_threshold 4.5 ratio
|
|
||||||
|
|
||||||
La valeur :code:`ratio` est comparée au rapport de contraste WCAG et va de
|
|
||||||
:code:`0.0 ratio` à :code:`21.0 ratio`. Le réglage n'agit que sur les couleurs
|
|
||||||
de premier plan : une couleur trop proche du fond est éclaircie ou assombrie
|
|
||||||
autant que nécessaire, en conservant sa teinte et sa saturation. Pour une
|
|
||||||
lisibilité maximale, on peut aussi choisir une palette explicite :
|
|
||||||
|
|
||||||
.. code-block:: conf
|
|
||||||
|
|
||||||
foreground #ffffff
|
|
||||||
background #000000
|
|
||||||
|
|
||||||
Mesures des rapports de contraste (formule WCAG 2.1, luminance relative) :
|
|
||||||
|
|
||||||
.. list-table::
|
|
||||||
:header-rows: 1
|
|
||||||
:widths: auto
|
|
||||||
|
|
||||||
* - Texte
|
|
||||||
- Fond
|
|
||||||
- Rapport
|
|
||||||
* - :code:`#ffffff`
|
|
||||||
- :code:`#000000`
|
|
||||||
- :code:`21.0:1` (niveau AAA)
|
|
||||||
* - :code:`#f8f8f2`
|
|
||||||
- :code:`#111111`
|
|
||||||
- :code:`17.7:1` (niveau AAA)
|
|
||||||
* - :code:`#dddddd`
|
|
||||||
- :code:`#111111`
|
|
||||||
- :code:`13.9:1` (niveau AAA)
|
|
||||||
|
|
||||||
Le seuil :code:`4.5 ratio` suffit donc pour le niveau AA quelle que soit la
|
|
||||||
palette, et ces trois combinaisons dépassent largement le niveau AAA.
|
|
||||||
|
|
||||||
.. note::
|
|
||||||
|
|
||||||
Certains programmes dessinent des graphismes avec des caractères de bloc en
|
|
||||||
mettant volontairement le texte et le fond de la même couleur. Le mode
|
|
||||||
:code:`ratio` conserve alors la teinte ; si un affichage paraît rayé ou
|
|
||||||
décoloré, préférez-le au mode :code:`%`, qui force le premier plan en blanc
|
|
||||||
ou en noir et peut casser ces graphismes.
|
|
||||||
|
|
||||||
Aucune régression par défaut
|
|
||||||
----------------------------
|
|
||||||
|
|
||||||
Le mode fort contraste est désactivé par défaut
|
|
||||||
(:opt:`text_fg_override_threshold` vaut :code:`0`) et la palette reste celle de
|
|
||||||
l'utilisateur. Les raccourcis ajoutés sont de nouvelles touches : les flèches et
|
|
||||||
les touches existantes continuent de fonctionner, et les captures d'écran par
|
|
||||||
défaut sont inchangées. Le mode ne s'active qu'en ajoutant la ligne
|
|
||||||
:code:`text_fg_override_threshold 4.5 ratio` à :file:`kitty.conf`.
|
|
||||||
@@ -222,57 +222,6 @@ Detailed list of changes
|
|||||||
0.50.1 [unreleased]
|
0.50.1 [unreleased]
|
||||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||||
|
|
||||||
- :opt:`notify_on_cmd_finish` is now enabled by default with the value
|
|
||||||
:code:`unfocused`: commands running longer than 5 seconds notify when the
|
|
||||||
window loses focus, without any configuration. Use :code:`never` to turn it
|
|
||||||
off.
|
|
||||||
|
|
||||||
- The :opt:`notify_on_cmd_finish` notification now reports how long the command
|
|
||||||
ran, next to the command line and the exit status it already showed. A shell
|
|
||||||
that ends a command without reporting a status (:code:`OSC 133;D` with no
|
|
||||||
argument) now shows :code:`0` instead of an empty status.
|
|
||||||
|
|
||||||
- kitty now keeps an in-memory history of the text copied to the clipboard,
|
|
||||||
which :ac:`paste_from_clipboard_history` and :ac:`search_clipboard_history`
|
|
||||||
can paste back. Nothing is written to disk and private clipboard writes are
|
|
||||||
never recorded. See :ref:`clipboard_history` for details.
|
|
||||||
|
|
||||||
- kitty now remembers the state of the session that was in use when it exited,
|
|
||||||
in :file:`$XDG_STATE_HOME/kitty/last-session.json`, so that
|
|
||||||
:code:`kitty --session=last` brings back the tabs, layouts, working
|
|
||||||
directories and titles of the previous run. Restoring is explicit, never
|
|
||||||
automatic, and a corrupt or oversized saved state is discarded instead of
|
|
||||||
blocking startup. See :ref:`sessions` for details.
|
|
||||||
|
|
||||||
- The :doc:`file manager <kittens/file-manager>` now keeps its directory in
|
|
||||||
step with the shell by default: a :code:`cd` moves the panel into the same
|
|
||||||
directory and walking through the panel moves the shell at its next prompt,
|
|
||||||
for bash, zsh and fish. Nothing is typed into the terminal, so no command
|
|
||||||
lands in the history and a multi-line command being typed is left untouched.
|
|
||||||
Set :code:`sync_cwd no` in :file:`file-manager.conf` to keep the two
|
|
||||||
directories independent, as before.
|
|
||||||
|
|
||||||
- :kbd:`Ctrl+Shift+E` now opens the :doc:`file manager kitten
|
|
||||||
<kittens/file-manager>` in a left dock by default, instead of requiring a
|
|
||||||
manual mapping. This takes the key over from :ac:`open_url`; remap
|
|
||||||
:kbd:`Ctrl+Shift+E` to :code:`open_url_with_hints` in :file:`kitty.conf` to
|
|
||||||
restore the previous behavior.
|
|
||||||
|
|
||||||
- The kitty shell now opens a searchable, categorized keyboard shortcut panel
|
|
||||||
in a side dock when :code:`help` is run without arguments, or when
|
|
||||||
:kbd:`kitty_mod+H` is pressed. The panel can also be started with
|
|
||||||
:code:`kitty +kitten help`.
|
|
||||||
|
|
||||||
- The default :opt:`tab_title_template` now shows the abbreviated working
|
|
||||||
directory of the tab before its title, so the directory indicator of the tab
|
|
||||||
bar is visible without configuration.
|
|
||||||
|
|
||||||
- Accessibility: :kbd:`Tab` and :kbd:`Shift+Tab` move the selection in the
|
|
||||||
:doc:`file manager <kittens/file-manager>` and the
|
|
||||||
:doc:`command palette <kittens/command-palette>` by default. A new
|
|
||||||
:doc:`accessibility guide </accessibility>` documents keyboard navigation and
|
|
||||||
the :opt:`text_fg_override_threshold` :code:`4.5 ratio` contrast mode.
|
|
||||||
|
|
||||||
- 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
|
||||||
@@ -281,17 +230,6 @@ Detailed list of changes
|
|||||||
that it stays usable in a dock. It also copies paths and creates, renames and
|
that it stays usable in a dock. It also copies paths and creates, renames and
|
||||||
deletes entries after a confirmation
|
deletes entries after a confirmation
|
||||||
|
|
||||||
- The :doc:`file manager <kittens/file-manager>` can now filter its listing
|
|
||||||
with a fuzzy query (:kbd:`/`), list and run its actions from an in-panel
|
|
||||||
palette (:kbd:`:`), and open the selected file in a new tab (:kbd:`O`) or a
|
|
||||||
new OS window (:kbd:`T`). Entries can also be sorted by size with
|
|
||||||
:code:`sort_by size`.
|
|
||||||
|
|
||||||
- The :doc:`file manager <kittens/file-manager>` documentation now covers its
|
|
||||||
shell integration and its limits (no preview, no volume handling, no
|
|
||||||
recursive deletion, no privileged files), and is listed in the kittens
|
|
||||||
overview next to the other built-in kittens.
|
|
||||||
|
|
||||||
- :doc:`choose-files <kittens/choose-files>`: Fix concurrent custom preview
|
- :doc:`choose-files <kittens/choose-files>`: Fix concurrent custom preview
|
||||||
commands occasionally receiving the path of a different file.
|
commands occasionally receiving the path of a different file.
|
||||||
|
|
||||||
|
|||||||
@@ -264,35 +264,3 @@ to access the clipboard.
|
|||||||
When the terminal sends an unsolicited paste event because the user triggered
|
When the terminal sends an unsolicited paste event because the user triggered
|
||||||
a paste and the 5522 mode is enabled, there will be no associated id. In this
|
a paste and the 5522 mode is enabled, there will be no associated id. In this
|
||||||
case, the multiplexer must forward the event to the currently active window.
|
case, the multiplexer must forward the event to the currently active window.
|
||||||
|
|
||||||
|
|
||||||
.. _clipboard_history:
|
|
||||||
|
|
||||||
Clipboard history
|
|
||||||
---------------------
|
|
||||||
|
|
||||||
kitty keeps the last 50 pieces of plain text copied to the clipboard of each
|
|
||||||
instance, newest first, and lets you paste one of them back with
|
|
||||||
:ac:`paste_from_clipboard_history`. :ac:`search_clipboard_history` filters the
|
|
||||||
history with a fuzzy query before showing the list.
|
|
||||||
|
|
||||||
The picker numbers the entries: type the number next to the entry you want to
|
|
||||||
paste, or press :kbd:`Escape` to cancel.
|
|
||||||
|
|
||||||
The history lives in memory only: it is never written to disk, so it disappears
|
|
||||||
when kitty exits and secrets copied during a session do not outlive it. Text
|
|
||||||
written by a program that marks its request as private (by passing a ``pw``
|
|
||||||
field in an *OSC 5522* write request) is never recorded, and neither is anything
|
|
||||||
copied to the primary selection. Images and other non-text data are ignored.
|
|
||||||
|
|
||||||
Both actions have a default shortcut: :kbd:`kitty_mod+alt+v` opens the
|
|
||||||
history and :kbd:`kitty_mod+alt+f` asks for a fuzzy query before showing the
|
|
||||||
list. To use different keys, add for example to :file:`kitty.conf`:
|
|
||||||
|
|
||||||
.. code-block:: conf
|
|
||||||
|
|
||||||
map kitty_mod+alt+h paste_from_clipboard_history
|
|
||||||
map kitty_mod+alt+g search_clipboard_history
|
|
||||||
|
|
||||||
The size of the history is fixed at 50 entries, 64 KiB per entry and 1 MiB in
|
|
||||||
total, so that a few large copies cannot use an unbounded amount of memory.
|
|
||||||
+1
-14
@@ -181,24 +181,11 @@ Variables que kitty définit en lançant des programmes enfants
|
|||||||
fonctions appelant :program:`kitty` fonctionnent correctement.
|
fonctions appelant :program:`kitty` fonctionnent correctement.
|
||||||
|
|
||||||
.. envvar:: KITTY_WINDOW_ID
|
.. envvar:: KITTY_WINDOW_ID
|
||||||
|
|
||||||
Un entier qui est l'identifiant de la :term:`fenêtre <window>` kitty dans
|
Un entier qui est l'identifiant de la :term:`fenêtre <window>` kitty dans
|
||||||
laquelle le programme s'exécute. Utilisable avec la :doc:`facilité de
|
laquelle le programme s'exécute. Utilisable avec la :doc:`facilité de
|
||||||
contrôle à distance de kitty <remote-control>`.
|
contrôle à distance de kitty <remote-control>`.
|
||||||
|
|
||||||
.. envvar:: KITTY_CWD_SYNC_DIR
|
|
||||||
|
|
||||||
Le répertoire de session dans lequel les shells et les kittens qui coopèrent
|
|
||||||
échangent leur répertoire courant, voir la :ref:`synchronisation du
|
|
||||||
gestionnaire de fichiers <file_manager>`. Il n'est lisible que par votre
|
|
||||||
utilisateur et disparaît à la fin de la session.
|
|
||||||
|
|
||||||
.. envvar:: KITTY_SPECIAL_WINDOW_PARENT
|
|
||||||
|
|
||||||
Un entier qui est l'identifiant de la :term:`fenêtre <window>` pour laquelle
|
|
||||||
une fenêtre spéciale (overlay ou dock) a été ouverte. Absent des fenêtres
|
|
||||||
normales ; le :doc:`gestionnaire de fichiers </kittens/file-manager>` s'en
|
|
||||||
sert pour retrouver le shell dont il suit le répertoire.
|
|
||||||
|
|
||||||
.. envvar:: KITTY_PID
|
.. envvar:: KITTY_PID
|
||||||
|
|
||||||
Un entier qui est l'identifiant du processus kitty dans lequel le programme
|
Un entier qui est l'identifiant du processus kitty dans lequel le programme
|
||||||
|
|||||||
@@ -18,7 +18,6 @@ The fast, feature-rich, GPU based terminal emulator.
|
|||||||
integrations
|
integrations
|
||||||
protocol-extensions
|
protocol-extensions
|
||||||
custom-shaders
|
custom-shaders
|
||||||
accessibility
|
|
||||||
press-mentions
|
press-mentions
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -88,9 +88,9 @@ The following keys are available while the command palette is open:
|
|||||||
- Run the selected action
|
- Run the selected action
|
||||||
* - :kbd:`Escape`
|
* - :kbd:`Escape`
|
||||||
- Clear the search query, or close the palette if the query is already empty
|
- Clear the search query, or close the palette if the query is already empty
|
||||||
* - :kbd:`Up` / :kbd:`Shift+Tab` / :kbd:`Ctrl+K` / :kbd:`Ctrl+P`
|
* - :kbd:`Up` / :kbd:`Ctrl+K` / :kbd:`Ctrl+P`
|
||||||
- Move selection up
|
- Move selection up
|
||||||
* - :kbd:`Down` / :kbd:`Tab` / :kbd:`Ctrl+J` / :kbd:`Ctrl+N`
|
* - :kbd:`Down` / :kbd:`Ctrl+J` / :kbd:`Ctrl+N`
|
||||||
- Move selection down
|
- Move selection down
|
||||||
* - :kbd:`Page Up`
|
* - :kbd:`Page Up`
|
||||||
- Move selection up by a page
|
- Move selection up by a page
|
||||||
|
|||||||
@@ -15,13 +15,10 @@ l'arborescence avec :kbd:`Entrée`, puis :kbd:`Ctrl+Entrée` ferme le panneau et
|
|||||||
déplace le shell, sans perdre l'environnement, l'historique ni l'état de la
|
déplace le shell, sans perdre l'environnement, l'historique ni l'état de la
|
||||||
session.
|
session.
|
||||||
|
|
||||||
Le raccourci par défaut :kbd:`Ctrl+Shift+E` ouvre le panneau dans un
|
Lancer le panneau avec :code:`kitten file-manager`, ou depuis une
|
||||||
:ref:`dock <docks>` à gauche de la fenêtre courante. On peut aussi le lancer
|
:ref:`fenêtre dockée <docks>` pour l'avoir en permanence à côté du shell::
|
||||||
avec :code:`kitten file-manager`, ou depuis une :ref:`fenêtre dockée <docks>`
|
|
||||||
pour l'avoir en permanence à côté du shell. Pour changer le raccourci ou le type
|
|
||||||
de lancement, redéfinissez-le dans :file:`kitty.conf`::
|
|
||||||
|
|
||||||
map ctrl+shift+e launch --type=overlay kitten file-manager
|
map ctrl+shift+e launch --type=window-dock --dock-edge=left --dock-size=60 kitten file-manager
|
||||||
|
|
||||||
Il peut aussi tourner dans un :doc:`panneau du bureau </kittens/panel>` ou dans
|
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.
|
||||||
@@ -35,8 +32,7 @@ est passé en argument ou avec ``--start-dir``.
|
|||||||
panneau a été lancé. Lancé dans un dock ou un panneau du bureau, il ne change
|
panneau a été lancé. Lancé dans un dock ou un panneau du bureau, il ne change
|
||||||
donc pas le répertoire du shell : :kbd:`Ctrl+Entrée` ferme le panneau sans
|
donc pas le répertoire du shell : :kbd:`Ctrl+Entrée` ferme le panneau sans
|
||||||
déplacer le shell. Lancez le panneau depuis une fenêtre de shell pour changer
|
déplacer le shell. Lancez le panneau depuis une fenêtre de shell pour changer
|
||||||
de répertoire, sauf si la synchronisation décrite plus bas est activée : le
|
de répertoire.
|
||||||
dock suit alors la fenêtre active du groupe au moment de sa création.
|
|
||||||
|
|
||||||
L'ouverture d'un fichier, elle, fonctionne partout : le panneau confie le
|
L'ouverture d'un fichier, elle, fonctionne partout : le panneau confie le
|
||||||
fichier à kitty, qui lance l'éditeur dans un nouvel onglet. Le fichier
|
fichier à kitty, qui lance l'éditeur dans un nouvel onglet. Le fichier
|
||||||
@@ -60,8 +56,7 @@ Actions
|
|||||||
utilisez :code:`sudo -e` depuis le shell.
|
utilisez :code:`sudo -e` depuis le shell.
|
||||||
|
|
||||||
:kbd:`→` ou :kbd:`L`
|
:kbd:`→` ou :kbd:`L`
|
||||||
descend dans le répertoire sélectionné ; le shell y va aussi, au prompt
|
descend dans le répertoire sélectionné sans toucher au shell.
|
||||||
suivant, quand la synchronisation est active.
|
|
||||||
|
|
||||||
: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.
|
||||||
@@ -70,33 +65,9 @@ Actions
|
|||||||
déplace le shell vers la sélection si c'est un répertoire, sinon vers le
|
déplace le shell vers la sélection si c'est un répertoire, sinon vers le
|
||||||
répertoire affiché, puis ferme le panneau.
|
répertoire affiché, puis ferme le panneau.
|
||||||
|
|
||||||
:kbd:`Tab` et :kbd:`Maj+Tab`
|
|
||||||
passent à l'entrée suivante, respectivement précédente, comme :kbd:`↓` et
|
|
||||||
:kbd:`↑`. Pendant la saisie d'un nom, la tabulation est ignorée : elle ne
|
|
||||||
peut pas faire partie d'un nom de fichier.
|
|
||||||
|
|
||||||
:kbd:`/`
|
|
||||||
filtre la liste à mesure de la saisie, avec la même recherche floue que la
|
|
||||||
palette de commandes. :kbd:`Entrée` ouvre la sélection, :kbd:`Échap`
|
|
||||||
efface la requête et rétablit la liste complète. Un nom de répertoire suivi
|
|
||||||
d'un :code:`/` ne filtre que les répertoires ; la requête est oubliée en
|
|
||||||
changeant de répertoire.
|
|
||||||
|
|
||||||
:kbd:`:`
|
|
||||||
ouvre la palette des actions. Elle liste chaque action avec sa description,
|
|
||||||
se filtre comme la recherche, et :kbd:`Entrée` exécute l'action
|
|
||||||
sélectionnée. La liste est la source unique utilisée par ce document :
|
|
||||||
toutes les actions configurables y figurent.
|
|
||||||
|
|
||||||
:kbd:`O` et :kbd:`T`
|
|
||||||
ouvrent le fichier sélectionné dans un nouvel onglet, respectivement une
|
|
||||||
nouvelle fenêtre du système. Sur un répertoire, elles y entrent sans
|
|
||||||
toucher au répertoire du shell.
|
|
||||||
|
|
||||||
:kbd:`N` et :kbd:`Maj+N`
|
:kbd:`N` et :kbd:`Maj+N`
|
||||||
créent un fichier, respectivement un répertoire, dans le répertoire
|
créent un fichier, respectivement un répertoire, dans le répertoire
|
||||||
affiché. Le nom se saisit dans la ligne d'état. :kbd:`A` est un alias de
|
affiché. Le nom se saisit dans la ligne d'état.
|
||||||
:kbd:`Maj+N`, pour les claviers où la combinaison est peu pratique.
|
|
||||||
|
|
||||||
:kbd:`R`
|
:kbd:`R`
|
||||||
renomme l'entrée sélectionnée.
|
renomme l'entrée sélectionnée.
|
||||||
@@ -113,49 +84,7 @@ Actions
|
|||||||
affiche ou masque les entrées cachées.
|
affiche ou masque les entrées cachées.
|
||||||
|
|
||||||
:kbd:`Échap` ou :kbd:`Q`
|
:kbd:`Échap` ou :kbd:`Q`
|
||||||
ferme le panneau sans rien changer : une demande de synchronisation que le
|
ferme le panneau sans rien changer.
|
||||||
shell n'a pas encore lue est retirée, il reste donc où il était.
|
|
||||||
|
|
||||||
|
|
||||||
Synchronisation avec le shell
|
|
||||||
------------------------------
|
|
||||||
|
|
||||||
Le panneau et le shell partagent leur répertoire courant depuis la version
|
|
||||||
0.50.1, dans les deux sens : un :code:`cd` dans le shell amène le panneau dans
|
|
||||||
le même répertoire, et chaque répertoire ouvert dans le panneau devient aussi
|
|
||||||
celui du shell, sans même avoir à valider. Pour que chacun garde son propre
|
|
||||||
répertoire, alors que le panneau part toujours de celui du shell et n'en change
|
|
||||||
plus ::
|
|
||||||
|
|
||||||
# ~/.config/kitty/file-manager.conf
|
|
||||||
sync_cwd no
|
|
||||||
|
|
||||||
L'échange ne passe pas par le terminal. kitty exporte un répertoire de session
|
|
||||||
dans :envvar:`KITTY_CWD_SYNC_DIR` ; le shell y publie son répertoire courant et
|
|
||||||
le panneau y dépose celui qu'il veut. Le panneau retrouve le shell qui l'a lancé
|
|
||||||
grâce à :envvar:`KITTY_SPECIAL_WINDOW_PARENT`. L'intégration shell de kitty, pour
|
|
||||||
bash, zsh et fish, applique la demande avec :code:`builtin cd` : aucune commande
|
|
||||||
n'entre dans l'historique et une commande multi-lignes en cours de saisie n'est
|
|
||||||
pas soumise.
|
|
||||||
|
|
||||||
.. note::
|
|
||||||
|
|
||||||
La synchronisation demande l'intégration shell de kitty, active par défaut
|
|
||||||
pour bash, zsh et fish. Les autres shells gardent le comportement précédent :
|
|
||||||
le panneau retape la commande :code:`cd` dans le terminal, comme lorsque
|
|
||||||
l'option est désactivée.
|
|
||||||
|
|
||||||
Le changement est appliqué au prompt suivant : le shell se déplace quand la
|
|
||||||
commande suivante démarre, ou qu'une ligne vide est validée, et non pendant
|
|
||||||
que vous parcourez le panneau. C'est le prix à payer pour ne jamais écrire
|
|
||||||
dans le terminal. Si vous quittez le panneau avec :kbd:`Échap` avant que le
|
|
||||||
shell ait lu la demande, elle est retirée et le shell ne bouge pas.
|
|
||||||
|
|
||||||
Lancé dans un dock, le panneau suit la fenêtre active du groupe au moment où
|
|
||||||
le dock est créé. Si vous passez ensuite à une autre fenêtre du même groupe,
|
|
||||||
il continue de suivre cette première fenêtre : relancez le dock pour changer
|
|
||||||
de cible. Dans un panneau du bureau, il n'y a pas de shell à suivre et la
|
|
||||||
synchronisation reste inerte.
|
|
||||||
|
|
||||||
|
|
||||||
.. _file-manager-shortcuts:
|
.. _file-manager-shortcuts:
|
||||||
@@ -179,19 +108,11 @@ Les actions disponibles sont :code:`quit`, :code:`move_up`, :code:`move_down`,
|
|||||||
:code:`page_up`, :code:`page_down`, :code:`home`, :code:`end`,
|
:code:`page_up`, :code:`page_down`, :code:`home`, :code:`end`,
|
||||||
:code:`activate`, :code:`enter_dir`, :code:`parent_dir`, :code:`cd_here`,
|
:code:`activate`, :code:`enter_dir`, :code:`parent_dir`, :code:`cd_here`,
|
||||||
:code:`toggle_hidden`, :code:`create_file`, :code:`create_dir`,
|
:code:`toggle_hidden`, :code:`create_file`, :code:`create_dir`,
|
||||||
:code:`rename`, :code:`delete`, :code:`copy_path`, :code:`refresh`,
|
:code:`rename`, :code:`delete`, :code:`copy_path` et :code:`refresh`.
|
||||||
:code:`search`, :code:`palette`, :code:`open_tab` et :code:`open_window`.
|
|
||||||
:code:`search`, :code:`palette`, :code:`open_tab` et :code:`open_window` sont
|
|
||||||
les actions des raccourcis :kbd:`/`, :kbd:`:`, :kbd:`O` et :kbd:`T`.
|
|
||||||
La palette :kbd:`:` liste ces actions avec leur description, ce qui évite de
|
|
||||||
retourner à ce document pour retrouver un nom.
|
|
||||||
|
|
||||||
Deux réglages d'apparence sont aussi disponibles : ``show_hidden`` affiche les
|
Deux réglages d'apparence sont aussi disponibles : ``show_hidden`` affiche les
|
||||||
entrées cachées à l'ouverture du panneau et ``sort_by`` vaut ``name`` (tri par
|
entrées cachées à l'ouverture du panneau et ``sort_by`` vaut ``name`` (tri par
|
||||||
nom en ignorant la casse), ``mtime`` (tri par date de dernière modification) ou
|
nom en ignorant la casse) ou ``mtime`` (tri par date de dernière modification).
|
||||||
``size`` (tri par taille, du plus gros au plus petit).
|
|
||||||
Les deux réglages peuvent être changés pour la session courante avec
|
|
||||||
:code:`-o show_hidden=yes` et :code:`-o sort_by=mtime`, ou :code:`-o sort_by=size`.
|
|
||||||
|
|
||||||
L'éditeur n'est pas choisi par le panneau : le fichier est confié à kitty, qui
|
L'éditeur n'est pas choisi par le panneau : le fichier est confié à kitty, qui
|
||||||
utilise son option :opt:`editor` de :file:`kitty.conf`. Quand celle-ci vaut
|
utilise son option :opt:`editor` de :file:`kitty.conf`. Quand celle-ci vaut
|
||||||
@@ -199,40 +120,6 @@ utilise son option :opt:`editor` de :file:`kitty.conf`. Quand celle-ci vaut
|
|||||||
avec repli sur le premier éditeur connu installé. Pour forcer nano, ajoutez
|
avec repli sur le premier éditeur connu installé. Pour forcer nano, ajoutez
|
||||||
:code:`editor nano` dans :file:`kitty.conf`.
|
:code:`editor nano` dans :file:`kitty.conf`.
|
||||||
|
|
||||||
Intégration au shell
|
|
||||||
---------------------
|
|
||||||
|
|
||||||
Le panneau ne lance pas de shell : il écrit dans le terminal de la fenêtre qui
|
|
||||||
l'a lancé. Lorsque le shell est au prompt (fin d'OSC :code:`133`), la commande
|
|
||||||
:code:`cd` est envoyée directement, comme si elle avait été tapée. Lorsqu'un
|
|
||||||
programme tourne, le texte est seulement collé, pour qu'il puisse être relu
|
|
||||||
plutôt que de tomber dans l'entrée standard de ce programme. L'intégration du
|
|
||||||
shell doit donc être active : elle l'est par défaut pour bash, zsh et fish
|
|
||||||
lancés par kitty.
|
|
||||||
|
|
||||||
Le répertoire de travail est transmis à la fenêtre d'origine uniquement, et
|
|
||||||
seulement pour les shells qui comprennent :code:`cd` avec un chemin entre
|
|
||||||
guillemets simples, c'est-à-dire les shells de type POSIX. Dans :code:`cmd.exe`
|
|
||||||
ou PowerShell, le panneau reste utilisable pour naviguer et ouvrir des fichiers,
|
|
||||||
mais la validation d'un répertoire ne change pas le répertoire courant.
|
|
||||||
|
|
||||||
Limites
|
|
||||||
-------
|
|
||||||
|
|
||||||
- Aucun aperçu du contenu des fichiers : seul le nom, le type et la date de
|
|
||||||
dernière modification sont affichés.
|
|
||||||
- Aucun montage ni démontage de volume, et aucune corbeille : la suppression est
|
|
||||||
immédiate, après confirmation.
|
|
||||||
- La suppression n'est jamais récursive ; un répertoire non vide provoque une
|
|
||||||
erreur.
|
|
||||||
- Les fichiers appartenant à root ne peuvent pas être ouverts : l'édition passe
|
|
||||||
par kitty et demande un accès en lecture et en écriture. Utilisez
|
|
||||||
:code:`sudo -e` depuis le shell.
|
|
||||||
- Lancé dans un dock ou un panneau du bureau, le panneau n'a pas de shell cible
|
|
||||||
pour changer de répertoire ; utilisez-le depuis une fenêtre de shell.
|
|
||||||
- Le panneau ne suit pas les modifications faites par d'autres programmes :
|
|
||||||
utilisez :kbd:`Ctrl+R` pour relire le répertoire.
|
|
||||||
|
|
||||||
.. include:: /generated/conf-kitten-file_manager.rst
|
.. include:: /generated/conf-kitten-file_manager.rst
|
||||||
|
|
||||||
.. include:: /generated/cli-kitten-file_manager.rst
|
.. include:: /generated/cli-kitten-file_manager.rst
|
||||||
@@ -1,54 +0,0 @@
|
|||||||
Panneau d'aide aux raccourcis
|
|
||||||
=============================
|
|
||||||
|
|
||||||
.. program:: kitty +kitten help
|
|
||||||
|
|
||||||
Le panneau d'aide affiche tous les raccourcis clavier actifs, triés par
|
|
||||||
catégorie, avec une recherche rapide. Il s'ouvre dans un dock latéral, comme le
|
|
||||||
gestionnaire de fichiers, et reste en lecture seule : :kbd:`Entrée` ne déclenche
|
|
||||||
aucune action. Il est mappé sur :kbd:`kitty_mod+H` (:kbd:`Ctrl+Shift+H` par
|
|
||||||
défaut).
|
|
||||||
|
|
||||||
Utilisation
|
|
||||||
-----------
|
|
||||||
|
|
||||||
Dans le :doc:`shell kitty </shell>` (:kbd:`Ctrl+Shift+Échap`), la commande
|
|
||||||
``help`` sans argument ouvre le panneau, tout comme :kbd:`kitty_mod+H` dans
|
|
||||||
n'importe quelle fenêtre ::
|
|
||||||
|
|
||||||
help
|
|
||||||
|
|
||||||
Depuis un terminal, lancez le kitten directement ::
|
|
||||||
|
|
||||||
kitty +kitten help
|
|
||||||
|
|
||||||
Pour l'ouvrir dans un dock depuis un raccourci de ``kitty.conf`` ::
|
|
||||||
|
|
||||||
map kitty_mod+f4 launch --type=window-dock --dock-edge=left --dock-size=60 kitty +kitten help
|
|
||||||
|
|
||||||
Commandes
|
|
||||||
---------
|
|
||||||
|
|
||||||
.. table::
|
|
||||||
|
|
||||||
===================== ===================================================
|
|
||||||
Touche Action
|
|
||||||
===================== ===================================================
|
|
||||||
Texte Filtre les raccourcis (recherche floue).
|
|
||||||
:kbd:`Entrée` Sans effet : le panneau est une référence.
|
|
||||||
:kbd:`Échap` Efface la requête, puis ferme le panneau.
|
|
||||||
:kbd:`↑`, :kbd:`↓` Sélectionne le raccourci précédent ou suivant.
|
|
||||||
:kbd:`Tab` Sélectionne le raccourci suivant.
|
|
||||||
:kbd:`Shift+Tab` Sélectionne le raccourci précédent.
|
|
||||||
:kbd:`Ctrl+K` Sélectionne le raccourci précédent.
|
|
||||||
:kbd:`Ctrl+J` Sélectionne le raccourci suivant.
|
|
||||||
:kbd:`Page↑` Défile d'une page vers le haut.
|
|
||||||
:kbd:`Page↓` Défile d'une page vers le bas.
|
|
||||||
:kbd:`Début` Premier raccourci.
|
|
||||||
:kbd:`Fin` Dernier raccourci.
|
|
||||||
:kbd:`F12` Affiche ou masque les actions sans raccourci.
|
|
||||||
===================== ===================================================
|
|
||||||
|
|
||||||
Les raccourcis affichés proviennent de la configuration effective de kitty :
|
|
||||||
les remappages de ``kitty.conf`` sont donc visibles. Les actions sans raccourci
|
|
||||||
sont masquées par défaut ; :kbd:`F12` les affiche.
|
|
||||||
@@ -14,12 +14,10 @@
|
|||||||
kittens/choose-fonts
|
kittens/choose-fonts
|
||||||
kittens/hints
|
kittens/hints
|
||||||
kittens/command-palette
|
kittens/command-palette
|
||||||
kittens/help
|
|
||||||
kittens/quick-access-terminal
|
kittens/quick-access-terminal
|
||||||
kittens/choose-files
|
kittens/choose-files
|
||||||
kittens/dnd
|
kittens/dnd
|
||||||
kittens/panel
|
kittens/panel
|
||||||
kittens/file-manager
|
|
||||||
kittens/remote_file
|
kittens/remote_file
|
||||||
kittens/hyperlinked_grep
|
kittens/hyperlinked_grep
|
||||||
kittens/transfer
|
kittens/transfer
|
||||||
@@ -67,11 +65,6 @@ et à créer des programmes autonomes utiles. Quelques kittens importants :
|
|||||||
depuis une seule surcouche de recherche.
|
depuis une seule surcouche de recherche.
|
||||||
|
|
||||||
|
|
||||||
:doc:`Aide aux raccourcis <kittens/help>`
|
|
||||||
Consultez tous les raccourcis clavier dans un panneau latéral, avec une
|
|
||||||
recherche rapide et un classement par catégorie.
|
|
||||||
|
|
||||||
|
|
||||||
:doc:`Terminal à accès rapide <kittens/quick-access-terminal>`
|
:doc:`Terminal à accès rapide <kittens/quick-access-terminal>`
|
||||||
Accédez à une fenêtre kitty flottante et semi-transparente d'accès rapide
|
Accédez à une fenêtre kitty flottante et semi-transparente d'accès rapide
|
||||||
avec une seule combinaison de touches.
|
avec une seule combinaison de touches.
|
||||||
@@ -123,9 +116,4 @@ et à créer des programmes autonomes utiles. Quelques kittens importants :
|
|||||||
:doc:`Presse-papiers <kittens/clipboard>`
|
:doc:`Presse-papiers <kittens/clipboard>`
|
||||||
Copiez/collez dans le presse-papiers depuis des scripts shell, même via SSH.
|
Copiez/collez dans le presse-papiers depuis des scripts shell, même via SSH.
|
||||||
|
|
||||||
|
|
||||||
:doc:`Gestionnaire de fichiers <kittens/file-manager>`
|
|
||||||
Parcourez les répertoires dans un panneau latéral et changez le répertoire
|
|
||||||
courant du shell sans quitter celui-ci.
|
|
||||||
|
|
||||||
Vous pouvez aussi :doc:`apprendre à créer vos propres kittens <kittens/custom>`.
|
Vous pouvez aussi :doc:`apprendre à créer vos propres kittens <kittens/custom>`.
|
||||||
@@ -34,30 +34,6 @@ you want to work on the project, simply run:
|
|||||||
|
|
||||||
You can also set the session in :file:`kitty.conf` via :opt:`startup_session`.
|
You can also set the session in :file:`kitty.conf` via :opt:`startup_session`.
|
||||||
|
|
||||||
Restoring the last session
|
|
||||||
----------------------------
|
|
||||||
|
|
||||||
kitty saves the state of its tabs, windows, layouts, working directories and
|
|
||||||
titles when it exits, in :file:`$XDG_STATE_HOME/kitty/last-session.json`
|
|
||||||
(usually :file:`~/.local/state/kitty/last-session.json`). The saved state is
|
|
||||||
limited to 1 MiB and is overwritten at every exit, so it never accumulates.
|
|
||||||
|
|
||||||
To restore it, start kitty with:
|
|
||||||
|
|
||||||
.. code-block:: sh
|
|
||||||
|
|
||||||
kitty --session=last
|
|
||||||
|
|
||||||
The same saved state can be restored inside a running kitty with the
|
|
||||||
:ac:`restore_last_session` action, which is mapped to :kbd:`kitty_mod+alt+r`
|
|
||||||
by default and adds the saved tabs to the current window.
|
|
||||||
|
|
||||||
Restoring is never automatic: without this option the saved state is ignored,
|
|
||||||
so an unexpected state is never imposed on you. A state file that is corrupt,
|
|
||||||
unreadable or too large is discarded and kitty starts normally. :code:`cd`
|
|
||||||
directives whose directory no longer exists are dropped when restoring. Use
|
|
||||||
:ac:`save_as_session` for sessions that must survive beyond the next exit.
|
|
||||||
|
|
||||||
Thus, it is very easy to create sessions and work on projects. To learn how to
|
Thus, it is very easy to create sessions and work on projects. To learn how to
|
||||||
create more complex sessions, see :ref:`complex_sessions`.
|
create more complex sessions, see :ref:`complex_sessions`.
|
||||||
|
|
||||||
|
|||||||
@@ -275,8 +275,6 @@ type Handler struct {
|
|||||||
cv *utils.CachedValues[*CachedSettings]
|
cv *utils.CachedValues[*CachedSettings]
|
||||||
shortcut_tracker config.ShortcutTracker
|
shortcut_tracker config.ShortcutTracker
|
||||||
keyboard_shortcuts []*config.KeyAction
|
keyboard_shortcuts []*config.KeyAction
|
||||||
read_only bool
|
|
||||||
data_file string
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 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.
|
||||||
@@ -289,30 +287,17 @@ func (h *Handler) initialize() (string, error) {
|
|||||||
h.lp.SetCursorVisible(true)
|
h.lp.SetCursorVisible(true)
|
||||||
h.lp.SetCursorShape(loop.BAR_CURSOR, true)
|
h.lp.SetCursorShape(loop.BAR_CURSOR, true)
|
||||||
h.lp.AllowLineWrapping(false)
|
h.lp.AllowLineWrapping(false)
|
||||||
title := "Command Palette"
|
h.lp.SetWindowTitle("Command Palette")
|
||||||
if h.read_only {
|
|
||||||
title = "Keyboard shortcuts"
|
|
||||||
}
|
|
||||||
h.lp.SetWindowTitle(title)
|
|
||||||
|
|
||||||
if h.read_only {
|
|
||||||
// A reference panel is about bindings, not about actions without one.
|
|
||||||
h.show_unmapped = false
|
|
||||||
} 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.
|
||||||
h.cv = utils.NewCachedValues("command-palette", &CachedSettings{ShowUnmapped: true})
|
h.cv = utils.NewCachedValues("command-palette", &CachedSettings{ShowUnmapped: true})
|
||||||
settings := h.cv.Load()
|
settings := h.cv.Load()
|
||||||
h.show_unmapped = settings.ShowUnmapped
|
h.show_unmapped = settings.ShowUnmapped
|
||||||
}
|
|
||||||
|
|
||||||
h.keyboard_shortcuts = config.ResolveShortcuts(NewConfig().KeyboardShortcuts)
|
h.keyboard_shortcuts = config.ResolveShortcuts(NewConfig().KeyboardShortcuts)
|
||||||
|
|
||||||
if h.data_file != "" {
|
if err := h.loadData(); err != nil {
|
||||||
if err := h.loadDataFile(); err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
} else if err := h.loadData(); err != nil {
|
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -328,23 +313,8 @@ func (h *Handler) loadData() error {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("failed to read stdin: %w", err)
|
return fmt.Errorf("failed to read stdin: %w", err)
|
||||||
}
|
}
|
||||||
return h.parseData(data)
|
|
||||||
}
|
|
||||||
|
|
||||||
// loadDataFile reads the JSON produced by the help kitten and removes it so
|
|
||||||
// that repeated launches do not leave temporary files behind.
|
|
||||||
func (h *Handler) loadDataFile() error {
|
|
||||||
data, err := os.ReadFile(h.data_file)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("failed to read keybinding data: %w", err)
|
|
||||||
}
|
|
||||||
_ = os.Remove(h.data_file)
|
|
||||||
return h.parseData(data)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *Handler) parseData(data []byte) error {
|
|
||||||
if len(data) == 0 {
|
if len(data) == 0 {
|
||||||
return fmt.Errorf("no keybinding data received")
|
return fmt.Errorf("no input data received on stdin; this kitten must be launched from kitty")
|
||||||
}
|
}
|
||||||
if err := json.Unmarshal(data, &h.input_data); err != nil {
|
if err := json.Unmarshal(data, &h.input_data); err != nil {
|
||||||
return fmt.Errorf("failed to parse input data: %w", err)
|
return fmt.Errorf("failed to parse input data: %w", err)
|
||||||
@@ -614,11 +584,8 @@ func (h *Handler) draw_screen() {
|
|||||||
if h.show_unmapped {
|
if h.show_unmapped {
|
||||||
unmappedToggleLabel = "Hide"
|
unmappedToggleLabel = "Hide"
|
||||||
}
|
}
|
||||||
footer := ""
|
footer := h.lp.SprintStyled("fg=bright-yellow", "[Enter]") + " Run " +
|
||||||
if !h.read_only {
|
h.lp.SprintStyled("fg=bright-yellow", "[Esc]") + " Quit " +
|
||||||
footer = h.lp.SprintStyled("fg=bright-yellow", "[Enter]") + " Run "
|
|
||||||
}
|
|
||||||
footer += h.lp.SprintStyled("fg=bright-yellow", "[Esc]") + " Quit " +
|
|
||||||
h.lp.SprintStyled("fg=bright-yellow", "\u2191\u2193") + " Navigate " +
|
h.lp.SprintStyled("fg=bright-yellow", "\u2191\u2193") + " Navigate " +
|
||||||
h.lp.SprintStyled("fg=bright-yellow", "[F12]") + " " + unmappedToggleLabel + " unmapped"
|
h.lp.SprintStyled("fg=bright-yellow", "[F12]") + " " + unmappedToggleLabel + " unmapped"
|
||||||
matchCount := ""
|
matchCount := ""
|
||||||
@@ -937,16 +904,11 @@ func (h *Handler) onKeyEvent(ev *loop.KeyEvent) error {
|
|||||||
h.moveSelection(-1)
|
h.moveSelection(-1)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
if ev.MatchesPressOrRepeat("down") || ev.MatchesPressOrRepeat("tab") {
|
if ev.MatchesPressOrRepeat("down") {
|
||||||
ev.Handled = true
|
ev.Handled = true
|
||||||
h.moveSelection(1)
|
h.moveSelection(1)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
if ev.MatchesPressOrRepeat("shift+tab") {
|
|
||||||
ev.Handled = true
|
|
||||||
h.moveSelection(-1)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
if ac := h.shortcut_tracker.Match(ev, h.keyboard_shortcuts); ac != nil {
|
if ac := h.shortcut_tracker.Match(ev, h.keyboard_shortcuts); ac != nil {
|
||||||
ev.Handled = true
|
ev.Handled = true
|
||||||
switch ac.Name {
|
switch ac.Name {
|
||||||
@@ -1038,10 +1000,6 @@ func (h *Handler) moveSelection(delta int) {
|
|||||||
|
|
||||||
// triggerSelected sets the selected binding's definition as the result and exits.
|
// triggerSelected sets the selected binding's definition as the result and exits.
|
||||||
func (h *Handler) triggerSelected() {
|
func (h *Handler) triggerSelected() {
|
||||||
if h.read_only {
|
|
||||||
h.lp.Beep()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
b := h.selectedBinding()
|
b := h.selectedBinding()
|
||||||
if b == nil || b.IsMouse {
|
if b == nil || b.IsMouse {
|
||||||
h.lp.Beep()
|
h.lp.Beep()
|
||||||
@@ -1053,7 +1011,7 @@ func (h *Handler) triggerSelected() {
|
|||||||
|
|
||||||
// main runs the command palette TUI as a kitty overlay.
|
// main runs the command palette TUI as a kitty overlay.
|
||||||
func main(cmd *cli.Command, opts *Options, args []string) (rc int, err error) {
|
func main(cmd *cli.Command, opts *Options, args []string) (rc int, err error) {
|
||||||
if opts.DataFile == "" && tty.IsTerminal(os.Stdin.Fd()) {
|
if tty.IsTerminal(os.Stdin.Fd()) {
|
||||||
return 1, fmt.Errorf("This kitten must only be run via the command_palette action mapped to a shortcut in kitty.conf")
|
return 1, fmt.Errorf("This kitten must only be run via the command_palette action mapped to a shortcut in kitty.conf")
|
||||||
}
|
}
|
||||||
output := tui.KittenOutputSerializer()
|
output := tui.KittenOutputSerializer()
|
||||||
@@ -1062,7 +1020,7 @@ func main(cmd *cli.Command, opts *Options, args []string) (rc int, err error) {
|
|||||||
return 1, err
|
return 1, err
|
||||||
}
|
}
|
||||||
|
|
||||||
handler := &Handler{lp: lp, read_only: opts.ReadOnly, data_file: opts.DataFile}
|
handler := &Handler{lp: lp}
|
||||||
lp.MouseTrackingMode(loop.FULL_MOUSE_TRACKING)
|
lp.MouseTrackingMode(loop.FULL_MOUSE_TRACKING)
|
||||||
|
|
||||||
lp.OnInitialize = func() (string, error) {
|
lp.OnInitialize = func() (string, error) {
|
||||||
|
|||||||
@@ -338,15 +338,6 @@ def handle_result(args: list[str], data: dict[str, Any], target_window_id: int,
|
|||||||
help_text = 'Browse and trigger keyboard shortcuts and actions'
|
help_text = 'Browse and trigger keyboard shortcuts and actions'
|
||||||
usage = ''
|
usage = ''
|
||||||
OPTIONS = r"""
|
OPTIONS = r"""
|
||||||
--data-file
|
|
||||||
Read keybinding data from this JSON file instead of STDIN. Used by the
|
|
||||||
keyboard shortcuts help panel, so that it can run in a dock window.
|
|
||||||
|
|
||||||
|
|
||||||
--read-only
|
|
||||||
type=bool-set
|
|
||||||
Display the bindings without running the selected action on Enter. The panel
|
|
||||||
is then a reference, not a launcher.
|
|
||||||
""".format
|
""".format
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -74,26 +74,6 @@ func (b *testHandlerBuilder) build() *Handler {
|
|||||||
return h
|
return h
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestParseData(t *testing.T) {
|
|
||||||
h := &Handler{}
|
|
||||||
data := []byte(`{"modes":{"":{"Cat":[{"key":"a","action":"x","action_display":"x","definition":"x"}]}},"mouse":[],"mode_order":[""],"category_order":{"":["Cat"]}}`)
|
|
||||||
if err := h.parseData(data); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if len(h.all_items) != 1 {
|
|
||||||
t.Fatalf("expected 1 item, got %d", len(h.all_items))
|
|
||||||
}
|
|
||||||
if b := h.all_items[0].binding; b.Key != "a" || b.Category != "Cat" {
|
|
||||||
t.Fatalf("unexpected binding: %+v", b)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestParseDataRejectsEmptyInput(t *testing.T) {
|
|
||||||
if err := (&Handler{}).parseData(nil); err == nil {
|
|
||||||
t.Fatal("expected an error for empty data")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func newTestHandler() *Handler {
|
func newTestHandler() *Handler {
|
||||||
return newBuilder().
|
return newBuilder().
|
||||||
addBinding("", "Copy/paste", testBinding("ctrl+shift+c", "copy_to_clipboard", "Copy the selected text from the active window to the clipboard")).
|
addBinding("", "Copy/paste", testBinding("ctrl+shift+c", "copy_to_clipboard", "Copy the selected text from the active window to the clipboard")).
|
||||||
|
|||||||
+46
-486
@@ -14,7 +14,6 @@ import (
|
|||||||
|
|
||||||
"github.com/kovidgoyal/kitty/tools/cli"
|
"github.com/kovidgoyal/kitty/tools/cli"
|
||||||
"github.com/kovidgoyal/kitty/tools/config"
|
"github.com/kovidgoyal/kitty/tools/config"
|
||||||
"github.com/kovidgoyal/kitty/tools/fzf"
|
|
||||||
"github.com/kovidgoyal/kitty/tools/tui"
|
"github.com/kovidgoyal/kitty/tools/tui"
|
||||||
"github.com/kovidgoyal/kitty/tools/tui/loop"
|
"github.com/kovidgoyal/kitty/tools/tui/loop"
|
||||||
"github.com/kovidgoyal/kitty/tools/wcswidth"
|
"github.com/kovidgoyal/kitty/tools/wcswidth"
|
||||||
@@ -28,7 +27,6 @@ type Entry struct {
|
|||||||
Name string
|
Name string
|
||||||
IsDir bool
|
IsDir bool
|
||||||
ModTime int64
|
ModTime int64
|
||||||
Size int64
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type input_purpose int
|
type input_purpose int
|
||||||
@@ -38,7 +36,6 @@ const (
|
|||||||
input_create_file
|
input_create_file
|
||||||
input_create_dir
|
input_create_dir
|
||||||
input_rename
|
input_rename
|
||||||
input_search
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// Pure helpers, kept free of terminal state so that they can be unit tested
|
// Pure helpers, kept free of terminal state so that they can be unit tested
|
||||||
@@ -54,16 +51,9 @@ func sort_entries(entries []Entry, sort_by string) {
|
|||||||
if a.IsDir != b.IsDir {
|
if a.IsDir != b.IsDir {
|
||||||
return a.IsDir
|
return a.IsDir
|
||||||
}
|
}
|
||||||
switch sort_by {
|
if sort_by == "mtime" && a.ModTime != b.ModTime {
|
||||||
case "mtime":
|
|
||||||
if a.ModTime != b.ModTime {
|
|
||||||
return a.ModTime > b.ModTime
|
return a.ModTime > b.ModTime
|
||||||
}
|
}
|
||||||
case "size":
|
|
||||||
if a.Size != b.Size {
|
|
||||||
return a.Size > b.Size
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return strings.ToLower(a.Name) < strings.ToLower(b.Name)
|
return strings.ToLower(a.Name) < strings.ToLower(b.Name)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -82,7 +72,6 @@ func read_dir(dir string, show_hidden bool, sort_by string) ([]Entry, error) {
|
|||||||
e := Entry{Name: name, IsDir: item.IsDir()}
|
e := Entry{Name: name, IsDir: item.IsDir()}
|
||||||
if info, ierr := item.Info(); ierr == nil {
|
if info, ierr := item.Info(); ierr == nil {
|
||||||
e.ModTime = info.ModTime().Unix()
|
e.ModTime = info.ModTime().Unix()
|
||||||
e.Size = info.Size()
|
|
||||||
}
|
}
|
||||||
entries = append(entries, e)
|
entries = append(entries, e)
|
||||||
}
|
}
|
||||||
@@ -202,28 +191,19 @@ type Handler struct {
|
|||||||
screen_size loop.ScreenSize
|
screen_size loop.ScreenSize
|
||||||
conf *Config
|
conf *Config
|
||||||
cwd string
|
cwd string
|
||||||
all_entries []Entry
|
|
||||||
entries []Entry
|
entries []Entry
|
||||||
selected int
|
selected int
|
||||||
scroll int
|
scroll int
|
||||||
show_hidden bool
|
show_hidden bool
|
||||||
search_query string
|
|
||||||
input_purpose input_purpose
|
input_purpose input_purpose
|
||||||
text_buffer string
|
text_buffer string
|
||||||
rename_source string
|
rename_source string
|
||||||
confirm_name string
|
confirm_name string
|
||||||
palette_open bool
|
|
||||||
palette_query string
|
|
||||||
palette []action_info
|
|
||||||
palette_selected int
|
|
||||||
message string
|
message string
|
||||||
result_action string
|
result_action string
|
||||||
result_path string
|
result_path string
|
||||||
shortcut_tracker config.ShortcutTracker
|
shortcut_tracker config.ShortcutTracker
|
||||||
keyboard_shortcuts []*config.KeyAction
|
keyboard_shortcuts []*config.KeyAction
|
||||||
sync *shell_sync
|
|
||||||
sync_handled bool
|
|
||||||
sync_published bool
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *Handler) initialize() (string, error) {
|
func (h *Handler) initialize() (string, error) {
|
||||||
@@ -238,69 +218,11 @@ func (h *Handler) initialize() (string, error) {
|
|||||||
if err = h.load(h.cwd); err != nil {
|
if err = h.load(h.cwd); err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
if h.sync != nil {
|
|
||||||
// Adopt the directory the shell is already in as the reference point so
|
|
||||||
// that an explicit --start-dir is not overridden by the first tick.
|
|
||||||
h.sync.last = h.sync.shell_cwd()
|
|
||||||
if _, err = h.lp.AddTimer(400*time.Millisecond, true, func(loop.IdType) error {
|
|
||||||
h.follow_shell_cwd()
|
|
||||||
return nil
|
|
||||||
}); err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
h.draw_screen()
|
h.draw_screen()
|
||||||
h.lp.SendOverlayReady()
|
h.lp.SendOverlayReady()
|
||||||
return "", nil
|
return "", nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// publish_browse hands the directory the user just opened in the panel to the
|
|
||||||
// shell, so that walking through the tree in the panel walks the shell through
|
|
||||||
// it too. The shell reads the request at its next prompt; until then the panel
|
|
||||||
// remembers it so that quitting can withdraw it.
|
|
||||||
func (h *Handler) publish_browse() {
|
|
||||||
if h.sync == nil || !h.sync.shell_has_hook() {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if err := h.sync.publish_request(h.cwd); err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
h.sync_published = true
|
|
||||||
}
|
|
||||||
|
|
||||||
// withdraw_sync_request drops a request published by browsing, so that leaving
|
|
||||||
// the panel without validating a directory leaves the shell where it was. It
|
|
||||||
// does nothing once the shell has read the request, which it only does at a
|
|
||||||
// prompt.
|
|
||||||
func (h *Handler) withdraw_sync_request() {
|
|
||||||
if !h.sync_published {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
h.sync.withdraw_request()
|
|
||||||
h.sync_published = false
|
|
||||||
}
|
|
||||||
|
|
||||||
// follow_shell_cwd mirrors a cd made in the shell into the panel, keeping the
|
|
||||||
// selection on the same name so that the cursor does not jump around.
|
|
||||||
func (h *Handler) follow_shell_cwd() {
|
|
||||||
if h.sync == nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
dir := h.sync.new_target(h.cwd)
|
|
||||||
if dir == "" {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
name := ""
|
|
||||||
if e, ok := h.selected_entry(); ok {
|
|
||||||
name = e.Name
|
|
||||||
}
|
|
||||||
if err := h.load(dir); err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
h.select_name(name)
|
|
||||||
h.draw_screen()
|
|
||||||
}
|
|
||||||
|
|
||||||
// load reads dir and adopts it as the current directory. Selection is clamped
|
// load reads dir and adopts it as the current directory. Selection is clamped
|
||||||
// rather than reset so that reloading a directory after an action keeps the
|
// rather than reset so that reloading a directory after an action keeps the
|
||||||
// cursor near where it was.
|
// cursor near where it was.
|
||||||
@@ -310,15 +232,9 @@ func (h *Handler) load(dir string) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
h.cwd = dir
|
h.cwd = dir
|
||||||
h.all_entries = entries
|
|
||||||
h.entries = entries
|
h.entries = entries
|
||||||
if h.search_query != "" {
|
if h.selected >= len(entries) {
|
||||||
if err = h.apply_search(); err != nil {
|
h.selected = max(0, len(entries)-1)
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if h.selected >= len(h.entries) {
|
|
||||||
h.selected = max(0, len(h.entries)-1)
|
|
||||||
}
|
}
|
||||||
if h.scroll > h.selected {
|
if h.scroll > h.selected {
|
||||||
h.scroll = h.selected
|
h.scroll = h.selected
|
||||||
@@ -361,8 +277,6 @@ func (h *Handler) reload() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (h *Handler) change_dir(dir string) {
|
func (h *Handler) change_dir(dir string) {
|
||||||
// A filter belongs to the directory it was typed in, not to the next one.
|
|
||||||
h.search_query, h.text_buffer, h.input_purpose = "", "", input_none
|
|
||||||
if err := h.load(dir); err != nil {
|
if err := h.load(dir); err != nil {
|
||||||
h.message = err.Error()
|
h.message = err.Error()
|
||||||
h.draw_screen()
|
h.draw_screen()
|
||||||
@@ -370,7 +284,6 @@ func (h *Handler) change_dir(dir string) {
|
|||||||
}
|
}
|
||||||
h.selected, h.scroll, h.message = 0, 0, ""
|
h.selected, h.scroll, h.message = 0, 0, ""
|
||||||
h.draw_screen()
|
h.draw_screen()
|
||||||
h.publish_browse()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *Handler) move_selection(delta int) {
|
func (h *Handler) move_selection(delta int) {
|
||||||
@@ -486,9 +399,6 @@ func (h *Handler) copy_selected_path() {
|
|||||||
// the panel, the selected file is opened in the editor. Enter used to quit the
|
// the panel, the selected file is opened in the editor. Enter used to quit the
|
||||||
// panel and cd the shell, which did nothing when the panel was docked.
|
// panel and cd the shell, which did nothing when the panel was docked.
|
||||||
func (h *Handler) activate() {
|
func (h *Handler) activate() {
|
||||||
if h.input_purpose == input_search {
|
|
||||||
h.stop_search()
|
|
||||||
}
|
|
||||||
e, ok := h.selected_entry()
|
e, ok := h.selected_entry()
|
||||||
if !ok {
|
if !ok {
|
||||||
h.lp.Beep()
|
h.lp.Beep()
|
||||||
@@ -501,24 +411,15 @@ func (h *Handler) activate() {
|
|||||||
h.open_file(entry_path(h.cwd, e.Name))
|
h.open_file(entry_path(h.cwd, e.Name))
|
||||||
}
|
}
|
||||||
|
|
||||||
// edit_args_in is the client side of kitty's edit protocol. The terminal opens
|
// edit_args is the client side of kitty's edit protocol. The terminal opens the
|
||||||
// the editor in a new tab or OS window, which gives the file a whole window even
|
// editor in a new tab, which gives the file a whole window even when the panel
|
||||||
// when the panel is docked. The window closes when the editor exits and the
|
// is docked. The tab closes when the editor exits and the panel is redrawn in
|
||||||
// panel is redrawn in place, instead of handing the command to the shell and
|
// place, instead of handing the command to the shell and disappearing.
|
||||||
// disappearing.
|
|
||||||
func edit_args_in(path, window_type string) []string {
|
|
||||||
return []string{"edit-in-kitty", "--type=" + window_type, path}
|
|
||||||
}
|
|
||||||
|
|
||||||
func edit_args(path string) []string {
|
func edit_args(path string) []string {
|
||||||
return edit_args_in(path, "tab")
|
return []string{"edit-in-kitty", "--type=tab", path}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *Handler) open_file(path string) {
|
func (h *Handler) open_file(path string) {
|
||||||
h.open_file_in(path, "tab")
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *Handler) open_file_in(path, window_type string) {
|
|
||||||
exe, err := os.Executable()
|
exe, err := os.Executable()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
h.message = err.Error()
|
h.message = err.Error()
|
||||||
@@ -528,7 +429,7 @@ func (h *Handler) open_file_in(path, window_type string) {
|
|||||||
// The loop must give up the tty while edit-in-kitty talks to the terminal,
|
// The loop must give up the tty while edit-in-kitty talks to the terminal,
|
||||||
// otherwise both processes compete for input and escape code responses.
|
// otherwise both processes compete for input and escape code responses.
|
||||||
err = h.lp.SuspendAndRun(func() error {
|
err = h.lp.SuspendAndRun(func() error {
|
||||||
cmd := exec.Command(exe, edit_args_in(path, window_type)...)
|
cmd := exec.Command(exe, edit_args(path)...)
|
||||||
cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr
|
cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr
|
||||||
return cmd.Run()
|
return cmd.Run()
|
||||||
})
|
})
|
||||||
@@ -545,8 +446,8 @@ func (h *Handler) open_file_in(path, window_type string) {
|
|||||||
h.draw_screen()
|
h.draw_screen()
|
||||||
}
|
}
|
||||||
|
|
||||||
// enter_dir browses into the selected directory inside the panel and hands it to
|
// enter_dir browses into the selected directory inside the panel, leaving the
|
||||||
// the shell, so that both stay on the same directory.
|
// working directory of the shell untouched.
|
||||||
func (h *Handler) enter_dir() {
|
func (h *Handler) enter_dir() {
|
||||||
e, ok := h.selected_entry()
|
e, ok := h.selected_entry()
|
||||||
if !ok || !e.IsDir {
|
if !ok || !e.IsDir {
|
||||||
@@ -558,14 +459,6 @@ func (h *Handler) enter_dir() {
|
|||||||
|
|
||||||
func (h *Handler) change_shell_dir_to(path string) {
|
func (h *Handler) change_shell_dir_to(path string) {
|
||||||
h.result_action, h.result_path = "cd", path
|
h.result_action, h.result_path = "cd", path
|
||||||
// With the sync on, the shell reads the request from its session file at the
|
|
||||||
// next prompt, so the handler must not also type the change into its pty.
|
|
||||||
// The request is only written once the shell proved it has the hook by
|
|
||||||
// publishing its directory: a shell without shell integration would
|
|
||||||
// otherwise never see it and the change would be silently lost.
|
|
||||||
if h.sync != nil && h.sync.shell_has_hook() && h.sync.publish_request(path) == nil {
|
|
||||||
h.sync_handled = true
|
|
||||||
}
|
|
||||||
h.lp.Quit(0)
|
h.lp.Quit(0)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -580,349 +473,53 @@ func (h *Handler) change_shell_dir() {
|
|||||||
h.change_shell_dir_to(path)
|
h.change_shell_dir_to(path)
|
||||||
}
|
}
|
||||||
|
|
||||||
type action_info struct {
|
func (h *Handler) perform_action(name string) {
|
||||||
Name string
|
switch name {
|
||||||
Description string
|
case "quit":
|
||||||
}
|
|
||||||
|
|
||||||
// action_catalog is the single source of truth shared by the in-panel palette
|
|
||||||
// and the documentation: every action accepted by perform_action has exactly
|
|
||||||
// one description here, and test_action_catalog enforces that.
|
|
||||||
var action_catalog = []action_info{
|
|
||||||
{"quit", "Close the panel without changing the shell directory"},
|
|
||||||
{"move_up", "Select the previous entry"},
|
|
||||||
{"move_down", "Select the next entry"},
|
|
||||||
{"page_up", "Move the selection up by one page"},
|
|
||||||
{"page_down", "Move the selection down by one page"},
|
|
||||||
{"home", "Select the first entry"},
|
|
||||||
{"end", "Select the last entry"},
|
|
||||||
{"activate", "Change the shell directory or open the selected file"},
|
|
||||||
{"enter_dir", "Browse into the selected directory"},
|
|
||||||
{"parent_dir", "Browse into the parent directory"},
|
|
||||||
{"cd_here", "Move the shell to the directory shown in the panel"},
|
|
||||||
{"toggle_hidden", "Show or hide entries whose name starts with a dot"},
|
|
||||||
{"create_file", "Create a file in the current directory"},
|
|
||||||
{"create_dir", "Create a directory in the current directory"},
|
|
||||||
{"rename", "Rename the selected entry"},
|
|
||||||
{"delete", "Delete the selected entry after confirmation"},
|
|
||||||
{"copy_path", "Copy the path of the selection to the clipboard"},
|
|
||||||
{"refresh", "Reload the current directory"},
|
|
||||||
{"search", "Filter the listing with a fuzzy query"},
|
|
||||||
{"palette", "List and run the actions of the panel"},
|
|
||||||
{"open_tab", "Open the selected file in a new tab"},
|
|
||||||
{"open_window", "Open the selected file in a new OS window"},
|
|
||||||
}
|
|
||||||
|
|
||||||
// Actions that need the panel state are plain functions of the handler, so the
|
|
||||||
// palette and the configurable shortcuts go through the same code path.
|
|
||||||
var action_handlers = map[string]func(*Handler){
|
|
||||||
"quit": func(h *Handler) {
|
|
||||||
h.withdraw_sync_request()
|
|
||||||
h.lp.Quit(0)
|
h.lp.Quit(0)
|
||||||
},
|
case "move_up":
|
||||||
"move_up": func(h *Handler) { h.move_selection(-1) },
|
h.move_selection(-1)
|
||||||
"move_down": func(h *Handler) { h.move_selection(1) },
|
case "move_down":
|
||||||
"page_up": func(h *Handler) {
|
h.move_selection(1)
|
||||||
|
case "page_up":
|
||||||
h.move_selection(-max(1, int(h.screen_size.HeightCells)-3))
|
h.move_selection(-max(1, int(h.screen_size.HeightCells)-3))
|
||||||
},
|
case "page_down":
|
||||||
"page_down": func(h *Handler) {
|
|
||||||
h.move_selection(max(1, int(h.screen_size.HeightCells)-3))
|
h.move_selection(max(1, int(h.screen_size.HeightCells)-3))
|
||||||
},
|
case "home":
|
||||||
"home": func(h *Handler) {
|
|
||||||
h.selected = 0
|
h.selected = 0
|
||||||
h.draw_screen()
|
h.draw_screen()
|
||||||
},
|
case "end":
|
||||||
"end": func(h *Handler) {
|
|
||||||
if len(h.entries) > 0 {
|
if len(h.entries) > 0 {
|
||||||
h.selected = len(h.entries) - 1
|
h.selected = len(h.entries) - 1
|
||||||
}
|
}
|
||||||
h.draw_screen()
|
h.draw_screen()
|
||||||
},
|
case "parent_dir":
|
||||||
"parent_dir": func(h *Handler) { h.change_dir(parent_of(h.cwd)) },
|
h.change_dir(parent_of(h.cwd))
|
||||||
"activate": func(h *Handler) { h.activate() },
|
case "activate":
|
||||||
"enter_dir": func(h *Handler) { h.enter_dir() },
|
|
||||||
"cd_here": func(h *Handler) { h.change_shell_dir() },
|
|
||||||
"toggle_hidden": func(h *Handler) { h.show_hidden = !h.show_hidden; h.reload() },
|
|
||||||
"create_file": func(h *Handler) { h.start_input(input_create_file) },
|
|
||||||
"create_dir": func(h *Handler) { h.start_input(input_create_dir) },
|
|
||||||
"rename": func(h *Handler) { h.start_rename() },
|
|
||||||
"delete": func(h *Handler) { h.start_delete() },
|
|
||||||
"copy_path": func(h *Handler) { h.copy_selected_path() },
|
|
||||||
"refresh": func(h *Handler) { h.reload() },
|
|
||||||
"search": func(h *Handler) { h.start_search() },
|
|
||||||
"palette": func(h *Handler) { h.open_palette() },
|
|
||||||
"open_tab": func(h *Handler) { h.open_selected("tab") },
|
|
||||||
"open_window": func(h *Handler) { h.open_selected("window") },
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *Handler) perform_action(name string) {
|
|
||||||
if fn, ok := action_handlers[name]; ok {
|
|
||||||
fn(h)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// filter_entries keeps the entries matching query, using the same fuzzy matcher
|
|
||||||
// as the command palette so that scoring stays consistent across kittens. An
|
|
||||||
// empty query keeps the listing untouched.
|
|
||||||
func filter_entries(entries []Entry, query string) ([]Entry, error) {
|
|
||||||
if query == "" {
|
|
||||||
return entries, nil
|
|
||||||
}
|
|
||||||
names := make([]string, len(entries))
|
|
||||||
for i, e := range entries {
|
|
||||||
names[i] = e.Name
|
|
||||||
if e.IsDir {
|
|
||||||
// Matching the trailing slash lets a query such as "src/" only
|
|
||||||
// select directories.
|
|
||||||
names[i] += "/"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
m := fzf.NewFuzzyMatcher(fzf.PATH_SCHEME)
|
|
||||||
results, err := m.Score(names, query)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
type scored_entry struct {
|
|
||||||
entry Entry
|
|
||||||
score uint
|
|
||||||
}
|
|
||||||
matches := make([]scored_entry, 0, len(entries))
|
|
||||||
for i, r := range results {
|
|
||||||
if r.Score > 0 {
|
|
||||||
matches = append(matches, scored_entry{entries[i], r.Score})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
sort.SliceStable(matches, func(i, j int) bool {
|
|
||||||
if matches[i].score != matches[j].score {
|
|
||||||
return matches[i].score > matches[j].score
|
|
||||||
}
|
|
||||||
return strings.ToLower(matches[i].entry.Name) < strings.ToLower(matches[j].entry.Name)
|
|
||||||
})
|
|
||||||
ans := make([]Entry, len(matches))
|
|
||||||
for i, m := range matches {
|
|
||||||
ans[i] = m.entry
|
|
||||||
}
|
|
||||||
return ans, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// filter_actions keeps the actions whose name or description matches query, most
|
|
||||||
// relevant first. An empty query lists the whole catalog.
|
|
||||||
func filter_actions(query string) ([]action_info, error) {
|
|
||||||
if query == "" {
|
|
||||||
return action_catalog, nil
|
|
||||||
}
|
|
||||||
texts := make([]string, len(action_catalog))
|
|
||||||
for i, a := range action_catalog {
|
|
||||||
texts[i] = a.Name + " " + a.Description
|
|
||||||
}
|
|
||||||
m := fzf.NewFuzzyMatcher(fzf.DEFAULT_SCHEME)
|
|
||||||
results, err := m.Score(texts, query)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
type scored_action struct {
|
|
||||||
action action_info
|
|
||||||
score uint
|
|
||||||
}
|
|
||||||
matches := make([]scored_action, 0, len(action_catalog))
|
|
||||||
for i, r := range results {
|
|
||||||
if r.Score > 0 {
|
|
||||||
matches = append(matches, scored_action{action_catalog[i], r.Score})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
sort.SliceStable(matches, func(i, j int) bool {
|
|
||||||
if matches[i].score != matches[j].score {
|
|
||||||
return matches[i].score > matches[j].score
|
|
||||||
}
|
|
||||||
return matches[i].action.Name < matches[j].action.Name
|
|
||||||
})
|
|
||||||
ans := make([]action_info, len(matches))
|
|
||||||
for i, m := range matches {
|
|
||||||
ans[i] = m.action
|
|
||||||
}
|
|
||||||
return ans, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *Handler) start_search() {
|
|
||||||
h.input_purpose = input_search
|
|
||||||
h.text_buffer, h.search_query = "", ""
|
|
||||||
h.entries = h.all_entries
|
|
||||||
h.selected, h.scroll, h.message = 0, 0, ""
|
|
||||||
h.draw_screen()
|
|
||||||
}
|
|
||||||
|
|
||||||
// apply_search filters the listing without redrawing, so that it can also be
|
|
||||||
// used from load() while the panel is being rebuilt.
|
|
||||||
func (h *Handler) apply_search() error {
|
|
||||||
entries, err := filter_entries(h.all_entries, h.search_query)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
h.entries = entries
|
|
||||||
h.selected = max(0, min(h.selected, len(h.entries)-1))
|
|
||||||
h.scroll = 0
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// stop_search clears the filter and restores the full listing, keeping the
|
|
||||||
// selection on the entry the user was looking at when it still exists.
|
|
||||||
func (h *Handler) stop_search() {
|
|
||||||
name := ""
|
|
||||||
if e, ok := h.selected_entry(); ok {
|
|
||||||
name = e.Name
|
|
||||||
}
|
|
||||||
h.input_purpose, h.text_buffer, h.search_query = input_none, "", ""
|
|
||||||
h.entries = h.all_entries
|
|
||||||
h.selected, h.scroll = 0, 0
|
|
||||||
h.select_name(name)
|
|
||||||
if h.selected >= len(h.entries) {
|
|
||||||
h.selected = max(0, len(h.entries)-1)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *Handler) handle_search_key(ev *loop.KeyEvent) error {
|
|
||||||
switch {
|
|
||||||
case ev.MatchesPressOrRepeat("escape"):
|
|
||||||
ev.Handled = true
|
|
||||||
h.stop_search()
|
|
||||||
h.draw_screen()
|
|
||||||
case ev.MatchesPressOrRepeat("enter"):
|
|
||||||
ev.Handled = true
|
|
||||||
h.activate()
|
h.activate()
|
||||||
case ev.MatchesPressOrRepeat("up"):
|
case "enter_dir":
|
||||||
ev.Handled = true
|
|
||||||
h.move_selection(-1)
|
|
||||||
case ev.MatchesPressOrRepeat("down"):
|
|
||||||
ev.Handled = true
|
|
||||||
h.move_selection(1)
|
|
||||||
case ev.MatchesPressOrRepeat("backspace"):
|
|
||||||
ev.Handled = true
|
|
||||||
if h.text_buffer != "" {
|
|
||||||
g := wcswidth.SplitIntoGraphemes(h.text_buffer)
|
|
||||||
h.text_buffer = strings.Join(g[:len(g)-1], "")
|
|
||||||
}
|
|
||||||
h.search_query = h.text_buffer
|
|
||||||
if err := h.apply_search(); err != nil {
|
|
||||||
h.message = err.Error()
|
|
||||||
}
|
|
||||||
h.draw_screen()
|
|
||||||
case ev.MatchesPressOrRepeat("tab"), ev.MatchesPressOrRepeat("shift+tab"):
|
|
||||||
// Tabs cannot be part of a query here, they move the selection.
|
|
||||||
ev.Handled = true
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *Handler) open_palette() {
|
|
||||||
h.palette_open = true
|
|
||||||
h.palette_query = ""
|
|
||||||
h.palette = action_catalog
|
|
||||||
h.palette_selected = 0
|
|
||||||
h.message = ""
|
|
||||||
h.draw_screen()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *Handler) close_palette() {
|
|
||||||
h.palette_open = false
|
|
||||||
h.palette_query = ""
|
|
||||||
h.palette = nil
|
|
||||||
h.palette_selected = 0
|
|
||||||
h.draw_screen()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *Handler) update_palette() {
|
|
||||||
actions, err := filter_actions(h.palette_query)
|
|
||||||
if err != nil {
|
|
||||||
h.message = err.Error()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
h.palette = actions
|
|
||||||
h.palette_selected = max(0, min(h.palette_selected, len(h.palette)-1))
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *Handler) run_palette_action() {
|
|
||||||
if h.palette_selected < 0 || h.palette_selected >= len(h.palette) {
|
|
||||||
h.close_palette()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
name := h.palette[h.palette_selected].Name
|
|
||||||
h.palette_open, h.palette_query, h.palette = false, "", nil
|
|
||||||
h.palette_selected = 0
|
|
||||||
h.perform_action(name)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *Handler) handle_palette_key(ev *loop.KeyEvent) error {
|
|
||||||
switch {
|
|
||||||
case ev.MatchesPressOrRepeat("escape"):
|
|
||||||
ev.Handled = true
|
|
||||||
h.close_palette()
|
|
||||||
case ev.MatchesPressOrRepeat("enter"):
|
|
||||||
ev.Handled = true
|
|
||||||
h.run_palette_action()
|
|
||||||
case ev.MatchesPressOrRepeat("up"):
|
|
||||||
ev.Handled = true
|
|
||||||
h.palette_selected = max(0, h.palette_selected-1)
|
|
||||||
h.draw_screen()
|
|
||||||
case ev.MatchesPressOrRepeat("down"):
|
|
||||||
ev.Handled = true
|
|
||||||
h.palette_selected = min(max(0, len(h.palette)-1), h.palette_selected+1)
|
|
||||||
h.draw_screen()
|
|
||||||
case ev.MatchesPressOrRepeat("backspace"):
|
|
||||||
ev.Handled = true
|
|
||||||
if h.palette_query != "" {
|
|
||||||
g := wcswidth.SplitIntoGraphemes(h.palette_query)
|
|
||||||
h.palette_query = strings.Join(g[:len(g)-1], "")
|
|
||||||
h.update_palette()
|
|
||||||
h.draw_screen()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// open_selected opens the selected file in the requested window type. The
|
|
||||||
// window type is a launch type, so "tab" and "window" both work.
|
|
||||||
func (h *Handler) open_selected(window_type string) {
|
|
||||||
e, ok := h.selected_entry()
|
|
||||||
if !ok {
|
|
||||||
h.lp.Beep()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if e.IsDir {
|
|
||||||
h.enter_dir()
|
h.enter_dir()
|
||||||
return
|
case "cd_here":
|
||||||
}
|
h.change_shell_dir()
|
||||||
h.open_file_in(entry_path(h.cwd, e.Name), window_type)
|
case "toggle_hidden":
|
||||||
}
|
h.show_hidden = !h.show_hidden
|
||||||
|
h.reload()
|
||||||
func (h *Handler) draw_palette_list(width, list_start, list_height int) {
|
case "create_file":
|
||||||
if len(h.palette) == 0 {
|
h.start_input(input_create_file)
|
||||||
return
|
case "create_dir":
|
||||||
}
|
h.start_input(input_create_dir)
|
||||||
offset := 0
|
case "rename":
|
||||||
if h.palette_selected >= list_height {
|
h.start_rename()
|
||||||
offset = h.palette_selected - list_height + 1
|
case "delete":
|
||||||
}
|
h.start_delete()
|
||||||
for row := 0; row < list_height; row++ {
|
case "copy_path":
|
||||||
idx := offset + row
|
h.copy_selected_path()
|
||||||
if idx >= len(h.palette) {
|
case "refresh":
|
||||||
break
|
h.reload()
|
||||||
}
|
|
||||||
a := h.palette[idx]
|
|
||||||
text := truncate_to_width(fmt.Sprintf("%-18s %s", a.Name, a.Description), width-2)
|
|
||||||
h.lp.MoveCursorTo(1, list_start+row)
|
|
||||||
if idx == h.palette_selected {
|
|
||||||
text += strings.Repeat(" ", max(0, width-wcswidth.Stringwidth(text)))
|
|
||||||
h.lp.QueueWriteString(h.lp.SprintStyled("reverse", text))
|
|
||||||
} else {
|
|
||||||
h.lp.QueueWriteString(" " + text)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *Handler) handle_input_key(ev *loop.KeyEvent) error {
|
func (h *Handler) handle_input_key(ev *loop.KeyEvent) error {
|
||||||
if h.input_purpose == input_search {
|
|
||||||
return h.handle_search_key(ev)
|
|
||||||
}
|
|
||||||
switch {
|
switch {
|
||||||
case ev.MatchesPressOrRepeat("escape"):
|
case ev.MatchesPressOrRepeat("escape"):
|
||||||
ev.Handled = true
|
ev.Handled = true
|
||||||
@@ -937,9 +534,6 @@ func (h *Handler) handle_input_key(ev *loop.KeyEvent) error {
|
|||||||
h.text_buffer = strings.Join(g[:len(g)-1], "")
|
h.text_buffer = strings.Join(g[:len(g)-1], "")
|
||||||
}
|
}
|
||||||
h.draw_screen()
|
h.draw_screen()
|
||||||
case ev.MatchesPressOrRepeat("tab"), ev.MatchesPressOrRepeat("shift+tab"):
|
|
||||||
// Tabs are not valid in file names, keep them out of the text buffer.
|
|
||||||
ev.Handled = true
|
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@@ -961,9 +555,6 @@ func (h *Handler) on_key_event(ev *loop.KeyEvent) error {
|
|||||||
if h.input_purpose != input_none {
|
if h.input_purpose != input_none {
|
||||||
return h.handle_input_key(ev)
|
return h.handle_input_key(ev)
|
||||||
}
|
}
|
||||||
if h.palette_open {
|
|
||||||
return h.handle_palette_key(ev)
|
|
||||||
}
|
|
||||||
if h.confirm_name != "" {
|
if h.confirm_name != "" {
|
||||||
return h.handle_confirm_key(ev)
|
return h.handle_confirm_key(ev)
|
||||||
}
|
}
|
||||||
@@ -1017,20 +608,8 @@ func (h *Handler) on_text(text string, from_key_event bool, in_bracketed_paste b
|
|||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
if h.palette_open {
|
|
||||||
h.palette_query += text
|
|
||||||
h.update_palette()
|
|
||||||
h.draw_screen()
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
if h.input_purpose != input_none {
|
if h.input_purpose != input_none {
|
||||||
h.text_buffer += text
|
h.text_buffer += text
|
||||||
if h.input_purpose == input_search {
|
|
||||||
h.search_query = h.text_buffer
|
|
||||||
if err := h.apply_search(); err != nil {
|
|
||||||
h.message = err.Error()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
h.draw_screen()
|
h.draw_screen()
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
@@ -1098,8 +677,6 @@ func (h *Handler) input_prompt() string {
|
|||||||
return "New directory:"
|
return "New directory:"
|
||||||
case input_rename:
|
case input_rename:
|
||||||
return fmt.Sprintf("Rename %s to:", h.rename_source)
|
return fmt.Sprintf("Rename %s to:", h.rename_source)
|
||||||
case input_search:
|
|
||||||
return "Search:"
|
|
||||||
}
|
}
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
@@ -1108,9 +685,6 @@ func (h *Handler) status_text() string {
|
|||||||
if h.message != "" {
|
if h.message != "" {
|
||||||
return " " + truncate_to_width(h.message, max(1, int(h.screen_size.WidthCells)-1))
|
return " " + truncate_to_width(h.message, max(1, int(h.screen_size.WidthCells)-1))
|
||||||
}
|
}
|
||||||
if h.search_query != "" {
|
|
||||||
return fmt.Sprintf(" /%s %d matches", h.search_query, len(h.entries))
|
|
||||||
}
|
|
||||||
if len(h.entries) == 0 {
|
if len(h.entries) == 0 {
|
||||||
return " Empty directory"
|
return " Empty directory"
|
||||||
}
|
}
|
||||||
@@ -1159,9 +733,6 @@ func (h *Handler) draw_screen() {
|
|||||||
}
|
}
|
||||||
h.scroll = max(0, min(h.scroll, max(0, len(h.entries)-list_height)))
|
h.scroll = max(0, min(h.scroll, max(0, len(h.entries)-list_height)))
|
||||||
|
|
||||||
if h.palette_open {
|
|
||||||
h.draw_palette_list(width, list_start, list_height)
|
|
||||||
} else {
|
|
||||||
for row := 0; row < list_height; row++ {
|
for row := 0; row < list_height; row++ {
|
||||||
idx := h.scroll + row
|
idx := h.scroll + row
|
||||||
if idx >= len(h.entries) {
|
if idx >= len(h.entries) {
|
||||||
@@ -1178,19 +749,12 @@ func (h *Handler) draw_screen() {
|
|||||||
h.lp.QueueWriteString(h.entry_text(e, width))
|
h.lp.QueueWriteString(h.entry_text(e, width))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
h.lp.MoveCursorTo(1, status_y)
|
h.lp.MoveCursorTo(1, status_y)
|
||||||
h.lp.QueueWriteString(h.lp.SprintStyled("dim", h.status_text()))
|
h.lp.QueueWriteString(h.lp.SprintStyled("dim", h.status_text()))
|
||||||
|
|
||||||
h.lp.MoveCursorTo(1, height)
|
h.lp.MoveCursorTo(1, height)
|
||||||
switch {
|
switch {
|
||||||
case h.palette_open:
|
|
||||||
prompt := "Actions: "
|
|
||||||
h.lp.SetCursorVisible(true)
|
|
||||||
h.lp.QueueWriteString(h.lp.SprintStyled("fg=bright-yellow", prompt))
|
|
||||||
h.lp.QueueWriteString(h.palette_query)
|
|
||||||
h.lp.MoveCursorTo(1+wcswidth.Stringwidth(prompt+h.palette_query), height)
|
|
||||||
case h.input_purpose != input_none:
|
case h.input_purpose != input_none:
|
||||||
prompt := h.input_prompt() + " "
|
prompt := h.input_prompt() + " "
|
||||||
h.lp.QueueWriteString(h.lp.SprintStyled("fg=bright-yellow", prompt))
|
h.lp.QueueWriteString(h.lp.SprintStyled("fg=bright-yellow", prompt))
|
||||||
@@ -1202,18 +766,14 @@ func (h *Handler) draw_screen() {
|
|||||||
h.lp.QueueWriteString(h.lp.SprintStyled("bold fg=bright-red", fmt.Sprintf("Delete %s? [y/N] ", h.confirm_name)))
|
h.lp.QueueWriteString(h.lp.SprintStyled("bold fg=bright-red", fmt.Sprintf("Delete %s? [y/N] ", h.confirm_name)))
|
||||||
default:
|
default:
|
||||||
h.lp.SetCursorVisible(false)
|
h.lp.SetCursorVisible(false)
|
||||||
hints := "Enter: open /: search :: actions ->: enter Ctrl+Enter: cd here <-: up .: hidden n: new file r: rename d: delete y: copy q: quit"
|
hints := "Enter: open ->: enter Ctrl+Enter: cd here <-: up .: hidden n: new file r: rename d: delete y: copy q: quit"
|
||||||
h.lp.QueueWriteString(h.lp.SprintStyled("dim", truncate_to_width(hints, width)))
|
h.lp.QueueWriteString(h.lp.SprintStyled("dim", truncate_to_width(hints, width)))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// result_payload is the JSON data handed over to the Python result handler.
|
// result_payload is the JSON data handed over to the Python result handler.
|
||||||
func (h *Handler) result_payload() map[string]string {
|
func (h *Handler) result_payload() map[string]string {
|
||||||
ans := map[string]string{"action": h.result_action, "path": h.result_path}
|
return map[string]string{"action": h.result_action, "path": h.result_path}
|
||||||
if h.sync_handled {
|
|
||||||
ans["sync"] = "1"
|
|
||||||
}
|
|
||||||
return ans
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func load_config(opts *Options) (*Config, error) {
|
func load_config(opts *Options) (*Config, error) {
|
||||||
@@ -1242,7 +802,7 @@ func main(_ *cli.Command, opts *Options, args []string) (rc int, err error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return 1, err
|
return 1, err
|
||||||
}
|
}
|
||||||
h := &Handler{lp: lp, conf: conf, cwd: start_dir, show_hidden: opts.ShowHidden || conf.Show_hidden, sync: new_shell_sync_from_env(conf.Sync_cwd)}
|
h := &Handler{lp: lp, conf: conf, cwd: start_dir, show_hidden: opts.ShowHidden || conf.Show_hidden}
|
||||||
h.keyboard_shortcuts = config.ResolveShortcuts(conf.KeyboardShortcuts)
|
h.keyboard_shortcuts = config.ResolveShortcuts(conf.KeyboardShortcuts)
|
||||||
lp.MouseTrackingMode(loop.FULL_MOUSE_TRACKING)
|
lp.MouseTrackingMode(loop.FULL_MOUSE_TRACKING)
|
||||||
|
|
||||||
|
|||||||
@@ -41,31 +41,7 @@ opt(
|
|||||||
long_text="""
|
long_text="""
|
||||||
How to order entries. :code:`name` lists directories first, then files, both
|
How to order entries. :code:`name` lists directories first, then files, both
|
||||||
sorted by name ignoring case. :code:`mtime` lists directories first, then files
|
sorted by name ignoring case. :code:`mtime` lists directories first, then files
|
||||||
sorted by last modification time, most recent first. :code:`size` lists
|
sorted by last modification time, most recent first.
|
||||||
directories first, then files sorted by size, largest first.
|
|
||||||
""",
|
|
||||||
)
|
|
||||||
|
|
||||||
egr()
|
|
||||||
|
|
||||||
agr('shell', 'Shell synchronisation')
|
|
||||||
|
|
||||||
opt(
|
|
||||||
'sync_cwd',
|
|
||||||
'yes',
|
|
||||||
option_type='to_bool',
|
|
||||||
long_text="""
|
|
||||||
Keep the shell's working directory and the panel in step. A :code:`cd` in the
|
|
||||||
shell moves the panel to the same directory, and walking through the panel moves
|
|
||||||
the shell to the directory being browsed at its next prompt. Quitting the panel
|
|
||||||
without validating a directory withdraws a request the shell has not read yet.
|
|
||||||
|
|
||||||
The exchange goes through two small files in the session directory kitty
|
|
||||||
exports as :envvar:`KITTY_CWD_SYNC_DIR`, so nothing is typed into the shell:
|
|
||||||
the command never lands in the history and a half typed multi-line command is
|
|
||||||
left untouched. Bash, zsh and fish are supported by their kitty shell
|
|
||||||
integration; other shells keep the current behaviour. Set :code:`sync_cwd no`
|
|
||||||
to keep the two directories independent.
|
|
||||||
""",
|
""",
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -105,8 +81,6 @@ map('Move selection up', 'move_up up move_up')
|
|||||||
map('Move selection up', 'move_up --allow-fallback=shifted,ascii k move_up')
|
map('Move selection up', 'move_up --allow-fallback=shifted,ascii k move_up')
|
||||||
map('Move selection down', 'move_down down move_down')
|
map('Move selection down', 'move_down down move_down')
|
||||||
map('Move selection down', 'move_down --allow-fallback=shifted,ascii j move_down')
|
map('Move selection down', 'move_down --allow-fallback=shifted,ascii j move_down')
|
||||||
map('Move selection up', 'move_up shift+tab move_up')
|
|
||||||
map('Move selection down', 'move_down tab move_down')
|
|
||||||
map('Move selection up by a page', 'page_up page_up page_up')
|
map('Move selection up by a page', 'page_up page_up page_up')
|
||||||
map('Move selection up by a page', 'page_up --allow-fallback=shifted,ascii ctrl+b page_up')
|
map('Move selection up by a page', 'page_up --allow-fallback=shifted,ascii ctrl+b page_up')
|
||||||
map('Move selection down by a page', 'page_down page_down page_down')
|
map('Move selection down by a page', 'page_down page_down page_down')
|
||||||
@@ -152,7 +126,6 @@ map('Change shell directory to the directory being browsed', 'cd_here --allow-fa
|
|||||||
map('Toggle display of hidden entries', 'toggle_hidden --allow-fallback=shifted,ascii . toggle_hidden')
|
map('Toggle display of hidden entries', 'toggle_hidden --allow-fallback=shifted,ascii . toggle_hidden')
|
||||||
map('Create a new file', 'create_file --allow-fallback=shifted,ascii n create_file')
|
map('Create a new file', 'create_file --allow-fallback=shifted,ascii n create_file')
|
||||||
map('Create a new directory', 'create_dir shift+n create_dir')
|
map('Create a new directory', 'create_dir shift+n create_dir')
|
||||||
map('Create a new directory', 'create_dir --allow-fallback=shifted,ascii a create_dir')
|
|
||||||
map('Rename the selected entry', 'rename --allow-fallback=shifted,ascii r rename')
|
map('Rename the selected entry', 'rename --allow-fallback=shifted,ascii r rename')
|
||||||
map(
|
map(
|
||||||
'Delete the selected entry',
|
'Delete the selected entry',
|
||||||
@@ -164,26 +137,6 @@ confirmation. Directories are never deleted recursively.
|
|||||||
)
|
)
|
||||||
map('Copy the path of the selection to the clipboard', 'copy_path --allow-fallback=shifted,ascii y copy_path')
|
map('Copy the path of the selection to the clipboard', 'copy_path --allow-fallback=shifted,ascii y copy_path')
|
||||||
map('Reload the current directory', 'refresh --allow-fallback=shifted,ascii ctrl+r refresh')
|
map('Reload the current directory', 'refresh --allow-fallback=shifted,ascii ctrl+r refresh')
|
||||||
map(
|
|
||||||
'Filter the listing with a fuzzy query',
|
|
||||||
'search --allow-fallback=shifted,ascii / search',
|
|
||||||
long_text="""
|
|
||||||
Filters the listing as text is typed, using the same fuzzy matcher as the
|
|
||||||
command palette. :kbd:`Entrée` opens the selection, :kbd:`Échap` clears the
|
|
||||||
query and restores the full listing.
|
|
||||||
""",
|
|
||||||
)
|
|
||||||
map(
|
|
||||||
'List and run the actions of the panel',
|
|
||||||
'palette --allow-fallback=shifted,ascii : palette',
|
|
||||||
long_text="""
|
|
||||||
Lists every action of the panel with its description, filtered by a fuzzy query,
|
|
||||||
and runs the selected one with :kbd:`Entrée`. The same actions can be bound to
|
|
||||||
dedicated shortcuts in :file:`file-manager.conf`.
|
|
||||||
""",
|
|
||||||
)
|
|
||||||
map('Open the selected file in a new tab', 'open_tab --allow-fallback=shifted,ascii o open_tab')
|
|
||||||
map('Open the selected file in a new OS window', 'open_window --allow-fallback=shifted,ascii t open_window')
|
|
||||||
|
|
||||||
egr()
|
egr()
|
||||||
|
|
||||||
@@ -242,10 +195,6 @@ def handle_result(args: list[str], data: dict[str, Any], target_window_id: int,
|
|||||||
action, path = data.get('action'), data.get('path')
|
action, path = data.get('action'), data.get('path')
|
||||||
if action != 'cd' or not path:
|
if action != 'cd' or not path:
|
||||||
return
|
return
|
||||||
if data.get('sync'):
|
|
||||||
# The panel published the directory in the session file and the shell
|
|
||||||
# picks it up from its prompt hook, see the sync_cwd option.
|
|
||||||
return
|
|
||||||
w = boss.window_id_map.get(target_window_id)
|
w = boss.window_id_map.get(target_window_id)
|
||||||
if w is None:
|
if w is None:
|
||||||
boss.ring_bell_if_allowed()
|
boss.ring_bell_if_allowed()
|
||||||
|
|||||||
@@ -3,11 +3,9 @@
|
|||||||
package file_manager
|
package file_manager
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestSortEntriesDirectoriesFirstThenByName(t *testing.T) {
|
func TestSortEntriesDirectoriesFirstThenByName(t *testing.T) {
|
||||||
@@ -182,19 +180,6 @@ func TestOpenWithSudoOption(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestSyncCwdIsOnByDefault(t *testing.T) {
|
|
||||||
c := NewConfig()
|
|
||||||
if !c.Sync_cwd {
|
|
||||||
t.Fatal("the panel must follow the shell by default")
|
|
||||||
}
|
|
||||||
if err := c.Parse("sync_cwd", "no"); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if c.Sync_cwd {
|
|
||||||
t.Fatal("sync_cwd = no must keep the two directories independent")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestEditArgs(t *testing.T) {
|
func TestEditArgs(t *testing.T) {
|
||||||
got := edit_args("/tmp/a.py")
|
got := edit_args("/tmp/a.py")
|
||||||
want := []string{"edit-in-kitty", "--type=tab", "/tmp/a.py"}
|
want := []string{"edit-in-kitty", "--type=tab", "/tmp/a.py"}
|
||||||
@@ -228,132 +213,6 @@ func TestResultPayload(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestSortEntriesBySize(t *testing.T) {
|
|
||||||
entries := []Entry{
|
|
||||||
{Name: "small.txt", Size: 10},
|
|
||||||
{Name: "large.txt", Size: 300},
|
|
||||||
{Name: "medium.txt", Size: 20},
|
|
||||||
{Name: "dir", IsDir: true, Size: 1},
|
|
||||||
}
|
|
||||||
sort_entries(entries, "size")
|
|
||||||
expected := []string{"dir", "large.txt", "medium.txt", "small.txt"}
|
|
||||||
for i, name := range expected {
|
|
||||||
if entries[i].Name != name {
|
|
||||||
t.Fatalf("wrong order at %d: wanted %s got %s", i, name, entries[i].Name)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestFilterEntries(t *testing.T) {
|
|
||||||
entries := []Entry{
|
|
||||||
{Name: "alpha.txt"},
|
|
||||||
{Name: "beta.txt"},
|
|
||||||
{Name: "zeta.md"},
|
|
||||||
{Name: "src", IsDir: true},
|
|
||||||
}
|
|
||||||
all, err := filter_entries(entries, "")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if len(all) != len(entries) {
|
|
||||||
t.Fatalf("an empty query must keep every entry, got %#v", all)
|
|
||||||
}
|
|
||||||
|
|
||||||
matches, err := filter_entries(entries, "bt")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if len(matches) != 1 || matches[0].Name != "beta.txt" {
|
|
||||||
t.Fatalf("unexpected matches for \"bt\": %#v", matches)
|
|
||||||
}
|
|
||||||
|
|
||||||
dirs, err := filter_entries(entries, "src/")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if len(dirs) != 1 || !dirs[0].IsDir {
|
|
||||||
t.Fatalf("a trailing slash must only match directories, got %#v", dirs)
|
|
||||||
}
|
|
||||||
|
|
||||||
none, err := filter_entries(entries, "zzz")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if len(none) != 0 {
|
|
||||||
t.Fatalf("a query that matches nothing must return nothing, got %#v", none)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestFilterEntriesLargeDirectory(t *testing.T) {
|
|
||||||
entries := make([]Entry, 10_000)
|
|
||||||
for i := range entries {
|
|
||||||
entries[i] = Entry{Name: fmt.Sprintf("file-%05d.txt", i)}
|
|
||||||
}
|
|
||||||
start := time.Now()
|
|
||||||
matches, err := filter_entries(entries, "file-099")
|
|
||||||
elapsed := time.Since(start)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if len(matches) == 0 {
|
|
||||||
t.Fatal("expected matches in a large directory")
|
|
||||||
}
|
|
||||||
if elapsed > 100*time.Millisecond {
|
|
||||||
t.Fatalf("filtering 10000 entries took %s, the limit is 100ms", elapsed)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestFilterActions(t *testing.T) {
|
|
||||||
all, err := filter_actions("")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if len(all) != len(action_catalog) {
|
|
||||||
t.Fatalf("an empty query must list the whole catalog, got %d of %d", len(all), len(action_catalog))
|
|
||||||
}
|
|
||||||
matches, err := filter_actions("delete")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if len(matches) == 0 || matches[0].Name != "delete" {
|
|
||||||
t.Fatalf("the palette must rank the delete action first, got %#v", matches)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestActionCatalogMatchesHandlers(t *testing.T) {
|
|
||||||
seen := make(map[string]bool, len(action_catalog))
|
|
||||||
for _, a := range action_catalog {
|
|
||||||
if a.Name == "" || a.Description == "" {
|
|
||||||
t.Fatalf("actions need a name and a description: %#v", a)
|
|
||||||
}
|
|
||||||
if seen[a.Name] {
|
|
||||||
t.Fatalf("duplicate action %q in the catalog", a.Name)
|
|
||||||
}
|
|
||||||
seen[a.Name] = true
|
|
||||||
if _, ok := action_handlers[a.Name]; !ok {
|
|
||||||
t.Fatalf("action %q is described but has no handler", a.Name)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for name := range action_handlers {
|
|
||||||
if !seen[name] {
|
|
||||||
t.Fatalf("action %q has a handler but no description in the palette", name)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestEditArgsInWindow(t *testing.T) {
|
|
||||||
got := edit_args_in("/tmp/a.py", "window")
|
|
||||||
want := []string{"edit-in-kitty", "--type=window", "/tmp/a.py"}
|
|
||||||
if len(got) != len(want) {
|
|
||||||
t.Fatalf("expected %#v, got %#v", want, got)
|
|
||||||
}
|
|
||||||
for i := range want {
|
|
||||||
if got[i] != want[i] {
|
|
||||||
t.Fatalf("expected %#v, got %#v", want, got)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestTruncateToWidth(t *testing.T) {
|
func TestTruncateToWidth(t *testing.T) {
|
||||||
if got := truncate_to_width("abcdef", 3); got != "ab\u2026" {
|
if got := truncate_to_width("abcdef", 3); got != "ab\u2026" {
|
||||||
t.Fatalf("unexpected truncation %q", got)
|
t.Fatalf("unexpected truncation %q", got)
|
||||||
|
|||||||
@@ -1,99 +0,0 @@
|
|||||||
// License: GPLv3 Copyright: 2026, FWS
|
|
||||||
|
|
||||||
package file_manager
|
|
||||||
|
|
||||||
import (
|
|
||||||
"os"
|
|
||||||
"path/filepath"
|
|
||||||
"strings"
|
|
||||||
)
|
|
||||||
|
|
||||||
// shell_sync is the file based channel between a shell and the panel. kitty
|
|
||||||
// exports KITTY_CWD_SYNC_DIR to every window and KITTY_SPECIAL_WINDOW_PARENT to
|
|
||||||
// the special windows it opens for another one, so both sides agree on two file
|
|
||||||
// names without a socket or a new protocol: the shell publishes its working
|
|
||||||
// directory in <dir>/<window id>, the panel publishes the directory it wants in
|
|
||||||
// <dir>/<window id>.set. The shell applies that request from its prompt hook,
|
|
||||||
// which keeps the command out of the history and leaves a half typed multi-line
|
|
||||||
// command alone.
|
|
||||||
type shell_sync struct {
|
|
||||||
dir string
|
|
||||||
window_id string
|
|
||||||
last string
|
|
||||||
}
|
|
||||||
|
|
||||||
func new_shell_sync(dir, window_id string, enabled bool) *shell_sync {
|
|
||||||
if !enabled || dir == "" || window_id == "" {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
if info, err := os.Stat(dir); err != nil || !info.IsDir() {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return &shell_sync{dir: dir, window_id: window_id}
|
|
||||||
}
|
|
||||||
|
|
||||||
// new_shell_sync_from_env is nil whenever the option is off or kitty did not
|
|
||||||
// give the panel a shell window to talk to, in which case the panel keeps its
|
|
||||||
// own behaviour and types the change into the shell instead.
|
|
||||||
func new_shell_sync_from_env(enabled bool) *shell_sync {
|
|
||||||
return new_shell_sync(os.Getenv("KITTY_CWD_SYNC_DIR"), os.Getenv("KITTY_SPECIAL_WINDOW_PARENT"), enabled)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *shell_sync) shell_cwd_path() string { return filepath.Join(s.dir, s.window_id) }
|
|
||||||
func (s *shell_sync) request_path() string { return s.shell_cwd_path() + ".set" }
|
|
||||||
|
|
||||||
// shell_has_hook reports whether the shell has published its working directory
|
|
||||||
// at least once, which only the integration hook does. Without it nothing would
|
|
||||||
// consume the request, so the panel has to type the change into the shell.
|
|
||||||
func (s *shell_sync) shell_has_hook() bool {
|
|
||||||
_, err := os.Stat(s.shell_cwd_path())
|
|
||||||
return err == nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// shell_cwd returns the working directory last published by the shell. An empty
|
|
||||||
// or relative path, or one that no longer exists, is treated as unknown rather
|
|
||||||
// than followed, as the shell may be between two writes.
|
|
||||||
func (s *shell_sync) shell_cwd() string {
|
|
||||||
b, err := os.ReadFile(s.shell_cwd_path())
|
|
||||||
if err != nil {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
p := strings.TrimSpace(string(b))
|
|
||||||
if !filepath.IsAbs(p) {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
if info, err := os.Stat(p); err != nil || !info.IsDir() {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
return p
|
|
||||||
}
|
|
||||||
|
|
||||||
// new_target returns the directory the panel should move to, or "" when the
|
|
||||||
// shell has not moved since the last call or already sits in current.
|
|
||||||
func (s *shell_sync) new_target(current string) string {
|
|
||||||
p := s.shell_cwd()
|
|
||||||
if p == "" || p == s.last {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
s.last = p
|
|
||||||
if p == current {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
return p
|
|
||||||
}
|
|
||||||
|
|
||||||
// publish_request hands a directory to the shell. The write goes through a
|
|
||||||
// temporary file so that the shell never reads a half written path.
|
|
||||||
func (s *shell_sync) publish_request(dir string) error {
|
|
||||||
tmp := s.request_path() + ".tmp"
|
|
||||||
if err := os.WriteFile(tmp, []byte(dir), 0o600); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return os.Rename(tmp, s.request_path())
|
|
||||||
}
|
|
||||||
|
|
||||||
// withdraw_request cancels a request the shell has not read yet. Removing a
|
|
||||||
// request it already consumed is not an error, the shell removes it itself.
|
|
||||||
func (s *shell_sync) withdraw_request() {
|
|
||||||
_ = os.Remove(s.request_path())
|
|
||||||
}
|
|
||||||
@@ -1,150 +0,0 @@
|
|||||||
// License: GPLv3 Copyright: 2026, FWS
|
|
||||||
|
|
||||||
package file_manager
|
|
||||||
|
|
||||||
import (
|
|
||||||
"os"
|
|
||||||
"path/filepath"
|
|
||||||
"testing"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestNewShellSyncNeedsOptionDirectoryAndWindow(t *testing.T) {
|
|
||||||
dir := t.TempDir()
|
|
||||||
if s := new_shell_sync(dir, "7", false); s != nil {
|
|
||||||
t.Fatal("the sync must stay off until the option is enabled")
|
|
||||||
}
|
|
||||||
if s := new_shell_sync("", "7", true); s != nil {
|
|
||||||
t.Fatal("the sync must be off without a session directory")
|
|
||||||
}
|
|
||||||
if s := new_shell_sync(dir, "", true); s != nil {
|
|
||||||
t.Fatal("the sync must be off without a shell window id")
|
|
||||||
}
|
|
||||||
if s := new_shell_sync(filepath.Join(dir, "missing"), "7", true); s != nil {
|
|
||||||
t.Fatal("the sync must be off when the session directory is missing")
|
|
||||||
}
|
|
||||||
if s := new_shell_sync(dir, "7", true); s == nil {
|
|
||||||
t.Fatal("the sync must be on with an option, a directory and a window id")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestPublishRequestIsReadableAndLeavesNoTemporaryFile(t *testing.T) {
|
|
||||||
dir := t.TempDir()
|
|
||||||
s := new_shell_sync(dir, "42", true)
|
|
||||||
if err := s.publish_request("/tmp/target dir"); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
got, err := os.ReadFile(filepath.Join(dir, "42.set"))
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if string(got) != "/tmp/target dir" {
|
|
||||||
t.Fatalf("unexpected request payload %q", got)
|
|
||||||
}
|
|
||||||
if _, err = os.Stat(filepath.Join(dir, "42.set.tmp")); err == nil {
|
|
||||||
t.Fatal("the temporary file must be renamed, not left behind")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestShellHasHookNeedsAPublishedDirectory(t *testing.T) {
|
|
||||||
dir := t.TempDir()
|
|
||||||
s := new_shell_sync(dir, "5", true)
|
|
||||||
if s.shell_has_hook() {
|
|
||||||
t.Fatal("the shell published nothing yet")
|
|
||||||
}
|
|
||||||
if err := s.publish_request(dir); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if s.shell_has_hook() {
|
|
||||||
t.Fatal("a request must not be mistaken for a published directory")
|
|
||||||
}
|
|
||||||
if err := os.WriteFile(filepath.Join(dir, "5"), []byte(dir), 0o600); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if !s.shell_has_hook() {
|
|
||||||
t.Fatal("a published directory means the shell has the hook")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestPublishBrowseNeedsTheShellHookAndCanBeWithdrawn(t *testing.T) {
|
|
||||||
dir := t.TempDir()
|
|
||||||
h := &Handler{sync: new_shell_sync(dir, "11", true), cwd: dir}
|
|
||||||
h.publish_browse()
|
|
||||||
if _, err := os.Stat(filepath.Join(dir, "11.set")); err == nil {
|
|
||||||
t.Fatal("the panel must not publish before the shell proved it has the hook")
|
|
||||||
}
|
|
||||||
if h.sync_published {
|
|
||||||
t.Fatal("nothing was published")
|
|
||||||
}
|
|
||||||
if err := os.WriteFile(filepath.Join(dir, "11"), []byte(dir), 0o600); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
h.publish_browse()
|
|
||||||
if got, err := os.ReadFile(filepath.Join(dir, "11.set")); err != nil || string(got) != dir {
|
|
||||||
t.Fatalf("unexpected request %q (%v)", got, err)
|
|
||||||
}
|
|
||||||
if !h.sync_published {
|
|
||||||
t.Fatal("the request must be remembered so that quitting can withdraw it")
|
|
||||||
}
|
|
||||||
h.withdraw_sync_request()
|
|
||||||
if _, err := os.Stat(filepath.Join(dir, "11.set")); err == nil {
|
|
||||||
t.Fatal("quitting must withdraw the pending request")
|
|
||||||
}
|
|
||||||
if h.sync_published {
|
|
||||||
t.Fatal("nothing is pending anymore")
|
|
||||||
}
|
|
||||||
h.withdraw_sync_request()
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestShellCwdIgnoresUnusablePaths(t *testing.T) {
|
|
||||||
dir := t.TempDir()
|
|
||||||
s := new_shell_sync(dir, "9", true)
|
|
||||||
published := filepath.Join(dir, "9")
|
|
||||||
for _, content := range []string{"", " \n", "relative/path", filepath.Join(dir, "gone")} {
|
|
||||||
if err := os.WriteFile(published, []byte(content), 0o600); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if got := s.shell_cwd(); got != "" {
|
|
||||||
t.Fatalf("%q must not be followed, got %q", content, got)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if got := s.shell_cwd(); got != "" {
|
|
||||||
t.Fatalf("a missing file must not be followed, got %q", got)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestNewTargetFollowsEachShellMoveOnce(t *testing.T) {
|
|
||||||
dir := t.TempDir()
|
|
||||||
s := new_shell_sync(dir, "3", true)
|
|
||||||
moved := t.TempDir()
|
|
||||||
s.last = dir
|
|
||||||
if got := s.new_target(dir); got != "" {
|
|
||||||
t.Fatalf("the shell has not moved yet, got %q", got)
|
|
||||||
}
|
|
||||||
if err := os.WriteFile(filepath.Join(dir, "3"), []byte(moved), 0o600); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if got := s.new_target(dir); got != moved {
|
|
||||||
t.Fatalf("wanted %q, got %q", moved, got)
|
|
||||||
}
|
|
||||||
if got := s.new_target(dir); got != "" {
|
|
||||||
t.Fatalf("a shell move must only be followed once, got %q", got)
|
|
||||||
}
|
|
||||||
if err := os.WriteFile(filepath.Join(dir, "3"), []byte(dir), 0o600); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if got := s.new_target(dir); got != "" {
|
|
||||||
t.Fatalf("moving to the directory already displayed must be a no-op, got %q", got)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestResultPayloadAdvertisesSyncOnlyWhenHandled(t *testing.T) {
|
|
||||||
h := &Handler{result_action: "cd", result_path: "/tmp"}
|
|
||||||
if payload := h.result_payload(); len(payload) != 2 {
|
|
||||||
t.Fatalf("the shell must be typed into when the sync did not handle the move: %#v", payload)
|
|
||||||
}
|
|
||||||
h.sync_handled = true
|
|
||||||
payload := h.result_payload()
|
|
||||||
if payload["sync"] != "1" || payload["path"] != "/tmp" {
|
|
||||||
t.Fatalf("unexpected payload: %#v", payload)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
# License: GPLv3 Copyright: 2026, FWS
|
|
||||||
@@ -1,47 +0,0 @@
|
|||||||
#!/usr/bin/env python
|
|
||||||
# License: GPLv3 Copyright: 2026, FWS
|
|
||||||
|
|
||||||
# The keybindings live in the Python options object, while the searchable list
|
|
||||||
# UI lives in the Go command palette. Collect the data here, then replace this
|
|
||||||
# process with the palette reading the same terminal, so the panel can run in a
|
|
||||||
# dock without a second protocol between the two.
|
|
||||||
|
|
||||||
import json
|
|
||||||
import os
|
|
||||||
import sys
|
|
||||||
import tempfile
|
|
||||||
from contextlib import suppress
|
|
||||||
|
|
||||||
help_text = 'Browse all keyboard shortcuts in a searchable panel'
|
|
||||||
usage = ''
|
|
||||||
OPTIONS = r"""
|
|
||||||
""".format
|
|
||||||
|
|
||||||
|
|
||||||
def main(args: list[str]) -> None:
|
|
||||||
from kittens.command_palette.main import collect_keys_data
|
|
||||||
from kitty.config import load_config
|
|
||||||
from kitty.constants import config_dir, kitten_exe
|
|
||||||
|
|
||||||
conf = os.path.join(config_dir, 'kitty.conf')
|
|
||||||
opts = load_config(conf) if os.path.exists(conf) else load_config()
|
|
||||||
fd, path = tempfile.mkstemp(prefix='kitty-shortcuts-', suffix='.json')
|
|
||||||
try:
|
|
||||||
with os.fdopen(fd, 'w', encoding='utf-8') as f:
|
|
||||||
json.dump(collect_keys_data(opts), f)
|
|
||||||
exe = kitten_exe()
|
|
||||||
os.execv(exe, [exe, 'command-palette', '--data-file=' + path, '--read-only'])
|
|
||||||
finally:
|
|
||||||
# execv only returns on failure; on success the Go side removes the file.
|
|
||||||
with suppress(OSError):
|
|
||||||
os.unlink(path)
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
|
||||||
main(sys.argv)
|
|
||||||
elif __name__ == '__doc__':
|
|
||||||
cd = sys.cli_docs # type: ignore
|
|
||||||
cd['usage'] = usage
|
|
||||||
cd['options'] = OPTIONS
|
|
||||||
cd['help_text'] = help_text
|
|
||||||
cd['short_desc'] = 'Browse all keyboard shortcuts in a searchable panel'
|
|
||||||
@@ -40,7 +40,6 @@ from .clipboard import (
|
|||||||
set_clipboard_string,
|
set_clipboard_string,
|
||||||
set_primary_selection,
|
set_primary_selection,
|
||||||
)
|
)
|
||||||
from .clipboard_history import ClipboardHistory
|
|
||||||
from .colors import ColorSchemes, theme_colors
|
from .colors import ColorSchemes, theme_colors
|
||||||
from .conf.utils import BadLine, KeyAction, to_cmdline
|
from .conf.utils import BadLine, KeyAction, to_cmdline
|
||||||
from .config import common_opts_as_dict, prepare_config_file_for_editing, store_effective_config
|
from .config import common_opts_as_dict, prepare_config_file_for_editing, store_effective_config
|
||||||
@@ -420,7 +419,6 @@ class Boss:
|
|||||||
self.atexit = Atexit()
|
self.atexit = Atexit()
|
||||||
set_layout_options(opts)
|
set_layout_options(opts)
|
||||||
self.clipboard = Clipboard()
|
self.clipboard = Clipboard()
|
||||||
self.clipboard_history = ClipboardHistory()
|
|
||||||
self.window_for_dispatch: Window | None = None
|
self.window_for_dispatch: Window | None = None
|
||||||
self.primary_selection = Clipboard(ClipboardType.primary_selection)
|
self.primary_selection = Clipboard(ClipboardType.primary_selection)
|
||||||
self.update_check_started = False
|
self.update_check_started = False
|
||||||
@@ -2530,7 +2528,6 @@ class Boss:
|
|||||||
if not self._call_on_quit_watchers({'confirmed': True}):
|
if not self._call_on_quit_watchers({'confirmed': True}):
|
||||||
set_application_quit_request(NO_CLOSE_REQUESTED)
|
set_application_quit_request(NO_CLOSE_REQUESTED)
|
||||||
return
|
return
|
||||||
self.save_last_session()
|
|
||||||
self.save_session_if_logging_out()
|
self.save_session_if_logging_out()
|
||||||
set_application_quit_request(IMPERATIVE_CLOSE_REQUESTED)
|
set_application_quit_request(IMPERATIVE_CLOSE_REQUESTED)
|
||||||
return
|
return
|
||||||
@@ -2560,20 +2557,9 @@ class Boss:
|
|||||||
if not self._call_on_quit_watchers({'confirmed': True}):
|
if not self._call_on_quit_watchers({'confirmed': True}):
|
||||||
set_application_quit_request(NO_CLOSE_REQUESTED)
|
set_application_quit_request(NO_CLOSE_REQUESTED)
|
||||||
return
|
return
|
||||||
self.save_last_session()
|
|
||||||
self.save_session_if_logging_out()
|
self.save_session_if_logging_out()
|
||||||
set_application_quit_request(IMPERATIVE_CLOSE_REQUESTED if confirmed else NO_CLOSE_REQUESTED)
|
set_application_quit_request(IMPERATIVE_CLOSE_REQUESTED if confirmed else NO_CLOSE_REQUESTED)
|
||||||
|
|
||||||
def save_last_session(self) -> None:
|
|
||||||
# Must run before the quit request is set: the C side then closes the windows and there is
|
|
||||||
# nothing left to serialize. Saving an empty session is a no-op, so this never clobbers a
|
|
||||||
# good state with a torn down one.
|
|
||||||
from .main import is_panel_kitten
|
|
||||||
from .session_restore import save_session_of
|
|
||||||
|
|
||||||
if not is_panel_kitten():
|
|
||||||
save_session_of(self)
|
|
||||||
|
|
||||||
def save_session_if_logging_out(self) -> None:
|
def save_session_if_logging_out(self) -> None:
|
||||||
from .logout_session import is_logout_in_progress
|
from .logout_session import is_logout_in_progress
|
||||||
|
|
||||||
@@ -3173,48 +3159,6 @@ class Boss:
|
|||||||
if text:
|
if text:
|
||||||
w.paste_with_actions(text)
|
w.paste_with_actions(text)
|
||||||
|
|
||||||
def _clipboard_history_preview(self, text: str) -> str:
|
|
||||||
# The picker shows one line per entry, so flatten newlines and keep the line short
|
|
||||||
q = ' '.join(text.split())
|
|
||||||
return q if len(q) <= 120 else q[:117] + '…'
|
|
||||||
|
|
||||||
def _choose_from_clipboard_history(self, entries: tuple[str, ...]) -> None:
|
|
||||||
if not entries:
|
|
||||||
self.ring_bell_if_allowed()
|
|
||||||
return
|
|
||||||
previews = [(text, self._clipboard_history_preview(text) or _('(blank)')) for text in entries]
|
|
||||||
# The picker is itself the active window while it is open, so keep the window the user was
|
|
||||||
# working in to paste into once it closes. The window can be gone by then.
|
|
||||||
target = self.window_for_dispatch or self.active_window
|
|
||||||
|
|
||||||
def chosen(text: str | None) -> None:
|
|
||||||
if text and target is not None:
|
|
||||||
w = self.window_id_map.get(target.id)
|
|
||||||
if w is not None:
|
|
||||||
w.paste_with_actions(text)
|
|
||||||
|
|
||||||
self.choose_entry(_('Clipboard history'), previews, chosen)
|
|
||||||
|
|
||||||
@ac('cp', 'Paste an entry from the clipboard history. See :ref:`clipboard_history`.')
|
|
||||||
def paste_from_clipboard_history(self) -> None:
|
|
||||||
self._choose_from_clipboard_history(self.clipboard_history.entries())
|
|
||||||
|
|
||||||
@ac('cp', 'Search the clipboard history and paste the selected entry. See :ref:`clipboard_history`.')
|
|
||||||
def search_clipboard_history(self) -> None:
|
|
||||||
if not self.clipboard_history:
|
|
||||||
self.ring_bell_if_allowed()
|
|
||||||
return
|
|
||||||
|
|
||||||
def query_entered(query: str) -> None:
|
|
||||||
self._choose_from_clipboard_history(self.clipboard_history.search(query))
|
|
||||||
|
|
||||||
self.get_line(
|
|
||||||
_('Search the clipboard history. Leave empty to list everything.'),
|
|
||||||
query_entered,
|
|
||||||
prompt=_('Search: '),
|
|
||||||
window_title=_('Search clipboard history'),
|
|
||||||
)
|
|
||||||
|
|
||||||
def current_primary_selection(self) -> str:
|
def current_primary_selection(self) -> str:
|
||||||
return get_primary_selection() if supports_primary_selection else ''
|
return get_primary_selection() if supports_primary_selection else ''
|
||||||
|
|
||||||
@@ -4003,13 +3947,6 @@ class Boss:
|
|||||||
def goto_session(self, *cmdline: str) -> None:
|
def goto_session(self, *cmdline: str) -> None:
|
||||||
goto_session(self, cmdline)
|
goto_session(self, cmdline)
|
||||||
|
|
||||||
@ac('session', 'Restore the tabs and windows of the session saved when kitty last quit. See :ref:`sessions`.')
|
|
||||||
def restore_last_session(self) -> None:
|
|
||||||
from .session_restore import restore_last_session_into
|
|
||||||
|
|
||||||
if not restore_last_session_into(self):
|
|
||||||
self.ring_bell_if_allowed()
|
|
||||||
|
|
||||||
@ac('session', 'Save the current kitty state as a session file. See :ref:`save_as_session`.')
|
@ac('session', 'Save the current kitty state as a session file. See :ref:`save_as_session`.')
|
||||||
def save_as_session(self, *cmdline: str) -> None:
|
def save_as_session(self, *cmdline: str) -> None:
|
||||||
save_as_session(self, cmdline)
|
save_as_session(self, cmdline)
|
||||||
|
|||||||
@@ -3,7 +3,6 @@
|
|||||||
|
|
||||||
import os
|
import os
|
||||||
import sys
|
import sys
|
||||||
import tempfile
|
|
||||||
import termios
|
import termios
|
||||||
from collections import defaultdict
|
from collections import defaultdict
|
||||||
from collections.abc import Callable, Generator, Iterable, Mapping, Sequence
|
from collections.abc import Callable, Generator, Iterable, Mapping, Sequence
|
||||||
@@ -22,20 +21,6 @@ if TYPE_CHECKING:
|
|||||||
from .window import CwdRequest
|
from .window import CwdRequest
|
||||||
|
|
||||||
|
|
||||||
@run_once
|
|
||||||
def cwd_sync_dir() -> str:
|
|
||||||
"""Directory shared by every window of this instance for the file manager's
|
|
||||||
working directory sync. It is created with private permissions so that only
|
|
||||||
this user can read the paths the shells publish, and lives in the runtime
|
|
||||||
directory, which the login session already clears. An empty string means the
|
|
||||||
sync is unavailable and the participating kittens keep their own behaviour."""
|
|
||||||
base = os.environ.get('XDG_RUNTIME_DIR')
|
|
||||||
try:
|
|
||||||
return tempfile.mkdtemp(prefix='kitty-cwd-sync-', dir=base if base and os.path.isdir(base) else None)
|
|
||||||
except OSError:
|
|
||||||
return ''
|
|
||||||
|
|
||||||
|
|
||||||
if is_macos:
|
if is_macos:
|
||||||
from kitty.fast_data_types import abspath_of_process as _abspath_of_process
|
from kitty.fast_data_types import abspath_of_process as _abspath_of_process
|
||||||
from kitty.fast_data_types import cmdline_of_process as cmdline_
|
from kitty.fast_data_types import cmdline_of_process as cmdline_
|
||||||
@@ -479,7 +464,6 @@ class Child:
|
|||||||
elif opts.terminfo_type == 'direct':
|
elif opts.terminfo_type == 'direct':
|
||||||
env['TERMINFO'] = base64_terminfo_data()
|
env['TERMINFO'] = base64_terminfo_data()
|
||||||
env['KITTY_INSTALLATION_DIR'] = kitty_base_dir
|
env['KITTY_INSTALLATION_DIR'] = kitty_base_dir
|
||||||
env['KITTY_CWD_SYNC_DIR'] = cwd_sync_dir()
|
|
||||||
self.unmodified_argv = list(self.argv)
|
self.unmodified_argv = list(self.argv)
|
||||||
if not self.should_run_via_run_shell_kitten and 'disabled' not in opts.shell_integration:
|
if not self.should_run_via_run_shell_kitten and 'disabled' not in opts.shell_integration:
|
||||||
from .shell_integration import modify_shell_environ
|
from .shell_integration import modify_shell_environ
|
||||||
|
|||||||
+4
-24
@@ -9,7 +9,6 @@ from gettext import gettext as _
|
|||||||
from tempfile import TemporaryFile
|
from tempfile import TemporaryFile
|
||||||
from typing import IO, NamedTuple, Union
|
from typing import IO, NamedTuple, Union
|
||||||
|
|
||||||
from .clipboard_history import text_from_mime_data
|
|
||||||
from .conf.utils import uniq
|
from .conf.utils import uniq
|
||||||
from .constants import supports_primary_selection
|
from .constants import supports_primary_selection
|
||||||
from .fast_data_types import (
|
from .fast_data_types import (
|
||||||
@@ -97,33 +96,15 @@ class Clipboard:
|
|||||||
self.clipboard_type = clipboard_type
|
self.clipboard_type = clipboard_type
|
||||||
self.enabled = self.clipboard_type is ClipboardType.clipboard or supports_primary_selection
|
self.enabled = self.clipboard_type is ClipboardType.clipboard or supports_primary_selection
|
||||||
|
|
||||||
def set_text(self, x: str | bytes, private: bool = False) -> None:
|
def set_text(self, x: str | bytes) -> None:
|
||||||
if isinstance(x, str):
|
if isinstance(x, str):
|
||||||
x = x.encode('utf-8')
|
x = x.encode('utf-8')
|
||||||
self.set_mime({'text/plain': x}, private=private)
|
self.set_mime({'text/plain': x})
|
||||||
|
|
||||||
def set_mime(self, data: Mapping[str, DataType], private: bool = False) -> None:
|
def set_mime(self, data: Mapping[str, DataType]) -> None:
|
||||||
if self.enabled and isinstance(data, dict):
|
if self.enabled and isinstance(data, dict):
|
||||||
self.data = dict(data)
|
self.data = dict(data)
|
||||||
set_clipboard_data_types(self.clipboard_type, tuple(self.data))
|
set_clipboard_data_types(self.clipboard_type, tuple(self.data))
|
||||||
self._record_in_history(private=private)
|
|
||||||
|
|
||||||
def _record_in_history(self, private: bool) -> None:
|
|
||||||
# Only plain text is useful in the history, and only for the clipboard: the primary selection
|
|
||||||
# changes constantly and would evict everything else. Private writes are dropped by the
|
|
||||||
# history itself, so that secrets never reach it.
|
|
||||||
if self.clipboard_type is not ClipboardType.clipboard:
|
|
||||||
return
|
|
||||||
if 'text/plain' not in self.data:
|
|
||||||
return
|
|
||||||
try:
|
|
||||||
# The payload can be a chunker rather than bytes, as writes are streamed from a temp file
|
|
||||||
text = text_from_mime_data(self.data['text/plain'])
|
|
||||||
history = getattr(get_boss(), 'clipboard_history', None)
|
|
||||||
except Exception:
|
|
||||||
return
|
|
||||||
if text and history is not None:
|
|
||||||
history.add(text, private=private)
|
|
||||||
|
|
||||||
def get_text(self) -> str:
|
def get_text(self) -> str:
|
||||||
parts: list[bytes] = []
|
parts: list[bytes] = []
|
||||||
@@ -328,8 +309,7 @@ class WriteRequest:
|
|||||||
if pos is not None:
|
if pos is not None:
|
||||||
self.mime_map[alias] = pos
|
self.mime_map[alias] = pos
|
||||||
x = {mime: self.tempfile.create_chunker(pos.start, pos.size) for mime, pos in self.mime_map.items()}
|
x = {mime: self.tempfile.create_chunker(pos.start, pos.size) for mime, pos in self.mime_map.items()}
|
||||||
# A write request that carries a password is private: never keep its data in the history
|
cp.set_mime(x)
|
||||||
cp.set_mime(x, private=bool(self.password))
|
|
||||||
|
|
||||||
def abort(self, msg: str) -> ValueError:
|
def abort(self, msg: str) -> ValueError:
|
||||||
# returns the error to raise, so that callers read as: raise self.abort(...)
|
# returns the error to raise, so that callers read as: raise self.abort(...)
|
||||||
|
|||||||
@@ -1,128 +0,0 @@
|
|||||||
#!/usr/bin/env python
|
|
||||||
# License: GPL v3 Copyright: 2026, Kovid Goyal <kovid at kovidgoyal.net>
|
|
||||||
|
|
||||||
# A bounded, in-memory history of what was copied to the clipboard.
|
|
||||||
#
|
|
||||||
# Nothing is ever written to disk: copied text often contains secrets and the history is meant to
|
|
||||||
# help within one kitty instance, not to outlive it. Entries marked private are never recorded.
|
|
||||||
|
|
||||||
from collections import deque
|
|
||||||
from contextlib import suppress
|
|
||||||
from typing import Iterator
|
|
||||||
|
|
||||||
DEFAULT_MAX_ENTRIES = 50
|
|
||||||
MAX_ENTRY_CHARS = 64 * 1024
|
|
||||||
MAX_TOTAL_CHARS = 1024 * 1024
|
|
||||||
|
|
||||||
|
|
||||||
def text_from_mime_data(data: object, max_chars: int = MAX_ENTRY_CHARS) -> str:
|
|
||||||
"""Extract text from a clipboard MIME payload, or an empty string when it is not text.
|
|
||||||
|
|
||||||
Clipboard payloads are either raw bytes or a factory returning a chunker, as the data can be
|
|
||||||
streamed from a temporary file. Only the start of the payload is materialized, since an entry
|
|
||||||
longer than max_chars is not kept anyway.
|
|
||||||
"""
|
|
||||||
limit = 4 * max_chars # a UTF-8 character takes at most four bytes
|
|
||||||
if isinstance(data, bytes | bytearray | memoryview):
|
|
||||||
raw = bytes(data[:limit])
|
|
||||||
elif callable(data):
|
|
||||||
chunks: list[bytes] = []
|
|
||||||
size = 0
|
|
||||||
chunker = data()
|
|
||||||
while True:
|
|
||||||
q = chunker()
|
|
||||||
if not q:
|
|
||||||
break
|
|
||||||
chunks.append(q)
|
|
||||||
size += len(q)
|
|
||||||
if size >= limit:
|
|
||||||
break
|
|
||||||
raw = b''.join(chunks)[:limit]
|
|
||||||
else:
|
|
||||||
return ''
|
|
||||||
return raw.decode('utf-8', 'replace')
|
|
||||||
|
|
||||||
|
|
||||||
def match_score(needle: str, haystack: str) -> int:
|
|
||||||
"""Return a score, lower is better, or -1 when haystack does not contain needle as a subsequence.
|
|
||||||
|
|
||||||
A plain substring match always scores better than a subsequence so that what the user typed as
|
|
||||||
a contiguous string is ranked first, which is what people expect from a fuzzy filter.
|
|
||||||
"""
|
|
||||||
if not needle:
|
|
||||||
return 0
|
|
||||||
needle, haystack = needle.lower(), haystack.lower()
|
|
||||||
pos = haystack.find(needle)
|
|
||||||
if pos > -1:
|
|
||||||
return pos
|
|
||||||
gaps = 0
|
|
||||||
start = 0
|
|
||||||
for ch in needle:
|
|
||||||
idx = haystack.find(ch, start)
|
|
||||||
if idx < 0:
|
|
||||||
return -1
|
|
||||||
gaps += idx - start
|
|
||||||
start = idx + 1
|
|
||||||
return MAX_TOTAL_CHARS + gaps
|
|
||||||
|
|
||||||
|
|
||||||
class ClipboardHistory:
|
|
||||||
def __init__(
|
|
||||||
self,
|
|
||||||
max_entries: int = DEFAULT_MAX_ENTRIES,
|
|
||||||
max_entry_chars: int = MAX_ENTRY_CHARS,
|
|
||||||
max_total_chars: int = MAX_TOTAL_CHARS,
|
|
||||||
) -> None:
|
|
||||||
self.max_entries = max(1, max_entries)
|
|
||||||
self.max_entry_chars = max(1, max_entry_chars)
|
|
||||||
self.max_total_chars = max(1, max_total_chars)
|
|
||||||
self._entries: deque[str] = deque()
|
|
||||||
self._total_chars = 0
|
|
||||||
|
|
||||||
def __len__(self) -> int:
|
|
||||||
return len(self._entries)
|
|
||||||
|
|
||||||
def __bool__(self) -> bool:
|
|
||||||
return bool(self._entries)
|
|
||||||
|
|
||||||
def __iter__(self) -> Iterator[str]:
|
|
||||||
return reversed(self._entries)
|
|
||||||
|
|
||||||
def __getitem__(self, idx: int) -> str:
|
|
||||||
return self.entries()[idx]
|
|
||||||
|
|
||||||
def entries(self) -> tuple[str, ...]:
|
|
||||||
"""All entries, most recently copied first."""
|
|
||||||
return tuple(reversed(self._entries))
|
|
||||||
|
|
||||||
def clear(self) -> None:
|
|
||||||
self._entries.clear()
|
|
||||||
self._total_chars = 0
|
|
||||||
|
|
||||||
def add(self, text: str, private: bool = False) -> bool:
|
|
||||||
"""Record text, returning False when it is deliberately not recorded."""
|
|
||||||
if private or not text or not text.strip():
|
|
||||||
return False
|
|
||||||
if len(text) > self.max_entry_chars:
|
|
||||||
return False
|
|
||||||
# A repeated copy moves the entry to the top instead of duplicating it
|
|
||||||
with suppress(ValueError):
|
|
||||||
self._entries.remove(text)
|
|
||||||
self._total_chars -= len(text)
|
|
||||||
self._entries.append(text)
|
|
||||||
self._total_chars += len(text)
|
|
||||||
while self._entries and (len(self._entries) > self.max_entries or self._total_chars > self.max_total_chars):
|
|
||||||
self._total_chars -= len(self._entries.popleft())
|
|
||||||
return True
|
|
||||||
|
|
||||||
def search(self, query: str) -> tuple[str, ...]:
|
|
||||||
"""Entries matching query, best match first, newest first among equal scores."""
|
|
||||||
if not query.strip():
|
|
||||||
return self.entries()
|
|
||||||
scored = []
|
|
||||||
for idx, text in enumerate(self.entries()):
|
|
||||||
score = match_score(query, text)
|
|
||||||
if score > -1:
|
|
||||||
scored.append((score, idx, text))
|
|
||||||
scored.sort(key=lambda x: (x[0], x[1]))
|
|
||||||
return tuple(text for _, _, text in scored)
|
|
||||||
@@ -86,7 +86,7 @@ def generate_class(defn: Definition, loc: str) -> tuple[str, str]:
|
|||||||
if isinstance(option, MultiOption):
|
if isinstance(option, MultiOption):
|
||||||
mval: dict[str, dict[str, Any]] = {'macos': {}, 'linux': {}, '': {}}
|
mval: dict[str, dict[str, Any]] = {'macos': {}, 'linux': {}, '': {}}
|
||||||
func, typ = option_type_data(option)
|
func, typ = option_type_data(option)
|
||||||
assert callable(func), getattr(func, '__name__', func)
|
assert isinstance(func, types.FunctionType)
|
||||||
for val in option:
|
for val in option:
|
||||||
if val.add_to_default:
|
if val.add_to_default:
|
||||||
gr = mval[val.only]
|
gr = mval[val.only]
|
||||||
@@ -115,7 +115,7 @@ def generate_class(defn: Definition, loc: str) -> tuple[str, str]:
|
|||||||
func = str
|
func = str
|
||||||
elif defn.has_color_table and option.is_color_table_color:
|
elif defn.has_color_table and option.is_color_table_color:
|
||||||
func, typ = option_type_data(option)
|
func, typ = option_type_data(option)
|
||||||
assert callable(func), getattr(func, '__name__', func)
|
assert isinstance(func, types.FunctionType)
|
||||||
t(f' ans[{option.name!r}] = {func.__name__}(val)')
|
t(f' ans[{option.name!r}] = {func.__name__}(val)')
|
||||||
tc_imports.add((func.__module__, func.__name__))
|
tc_imports.add((func.__module__, func.__name__))
|
||||||
cnum = int(option.name[5:])
|
cnum = int(option.name[5:])
|
||||||
@@ -130,7 +130,7 @@ def generate_class(defn: Definition, loc: str) -> tuple[str, str]:
|
|||||||
params = dict(inspect.signature(func).parameters)
|
params = dict(inspect.signature(func).parameters)
|
||||||
except Exception:
|
except Exception:
|
||||||
params = {}
|
params = {}
|
||||||
assert callable(func), getattr(func, '__name__', func)
|
assert isinstance(func, types.FunctionType)
|
||||||
if 'dict_with_parse_results' in params:
|
if 'dict_with_parse_results' in params:
|
||||||
t(f' {func.__name__}(val, ans)')
|
t(f' {func.__name__}(val, ans)')
|
||||||
else:
|
else:
|
||||||
@@ -188,7 +188,7 @@ def generate_class(defn: Definition, loc: str) -> tuple[str, str]:
|
|||||||
for aname, action in defn.actions.items():
|
for aname, action in defn.actions.items():
|
||||||
option_names.add(aname)
|
option_names.add(aname)
|
||||||
action_parsers[aname] = func = action.parser_func
|
action_parsers[aname] = func = action.parser_func
|
||||||
assert callable(func), getattr(func, '__name__', func)
|
assert isinstance(func, types.FunctionType)
|
||||||
th = get_type_hints(func)
|
th = get_type_hints(func)
|
||||||
rettype = th['return']
|
rettype = th['return']
|
||||||
typ = option_type_as_str(rettype)
|
typ = option_type_as_str(rettype)
|
||||||
|
|||||||
+6
-2
@@ -215,7 +215,9 @@ def parse_profile_lines(
|
|||||||
# resolve includes against, so let the parser fall back to config_dir.
|
# resolve includes against, so let the parser fall back to config_dir.
|
||||||
name = file if file and file != '-' and not file.startswith('<') else ''
|
name = file if file and file != '-' and not file.startswith('<') else ''
|
||||||
with currently_parsing.set_file(name):
|
with currently_parsing.set_file(name):
|
||||||
vals = parse_config(NamedLineIterator(name, iter(group)), accumulate_bad_lines=accumulate_bad_lines, effective_config_lines=effective_config_lines)
|
vals = parse_config(
|
||||||
|
NamedLineIterator(name, iter(group)), accumulate_bad_lines=accumulate_bad_lines, effective_config_lines=effective_config_lines
|
||||||
|
)
|
||||||
for k, v in vals.items():
|
for k, v in vals.items():
|
||||||
if isinstance(v, dict):
|
if isinstance(v, dict):
|
||||||
ans.setdefault(k, {}).update(v)
|
ans.setdefault(k, {}).update(v)
|
||||||
@@ -229,7 +231,9 @@ def parse_profile_lines(
|
|||||||
effective_config_lines: list[str] = []
|
effective_config_lines: list[str] = []
|
||||||
|
|
||||||
|
|
||||||
def load_config(*paths: str, overrides: Iterable[str] | None = None, accumulate_bad_lines: list[BadLine] | None = None, profile: str | None = None) -> Options:
|
def load_config(
|
||||||
|
*paths: str, overrides: Iterable[str] | None = None, accumulate_bad_lines: list[BadLine] | None = None, profile: str | None = None
|
||||||
|
) -> Options:
|
||||||
from .options.parse import merge_result_dicts
|
from .options.parse import merge_result_dicts
|
||||||
from .options.types import secret_options
|
from .options.types import secret_options
|
||||||
|
|
||||||
|
|||||||
@@ -424,10 +424,8 @@ handle_fast_commandline(CLISpec *cli_spec, const char *instance_group_prefix) {
|
|||||||
if (get_bool_cli_val(cli_spec, "version")) {
|
if (get_bool_cli_val(cli_spec, "version")) {
|
||||||
if (isatty(STDOUT_FILENO)) {
|
if (isatty(STDOUT_FILENO)) {
|
||||||
printf("\x1b[3mkitty\x1b[23m \x1b[32m%s\x1b[39m created by \x1b[1;34mKovid Goyal\x1b[22;39m\n", KITTY_VERSION);
|
printf("\x1b[3mkitty\x1b[23m \x1b[32m%s\x1b[39m created by \x1b[1;34mKovid Goyal\x1b[22;39m\n", KITTY_VERSION);
|
||||||
printf("\x1b[3mfws-kitty\x1b[23m \x1b[32m0.1.6\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");
|
|
||||||
}
|
}
|
||||||
exit(0);
|
exit(0);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -68,7 +68,6 @@ from .options.types import Options
|
|||||||
from .options.utils import DELETE_ENV_VAR
|
from .options.utils import DELETE_ENV_VAR
|
||||||
from .os_window_size import edge_spacing, initial_window_size_func
|
from .os_window_size import edge_spacing, initial_window_size_func
|
||||||
from .session import create_sessions, get_os_window_sizing_data
|
from .session import create_sessions, get_os_window_sizing_data
|
||||||
from .session_restore import save_session_of
|
|
||||||
from .shaders.slang import load_shader_programs
|
from .shaders.slang import load_shader_programs
|
||||||
from .types import LayerShellConfig
|
from .types import LayerShellConfig
|
||||||
from .utils import (
|
from .utils import (
|
||||||
@@ -395,8 +394,6 @@ def _run_app(opts: Options, args: CLIOptions, bad_lines: Sequence[BadLine] = (),
|
|||||||
try:
|
try:
|
||||||
boss.child_monitor.main_loop()
|
boss.child_monitor.main_loop()
|
||||||
finally:
|
finally:
|
||||||
if not _is_panel_kitten:
|
|
||||||
save_session_of(boss)
|
|
||||||
boss.destroy()
|
boss.destroy()
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -2450,7 +2450,7 @@ lines is wrapped independently.
|
|||||||
|
|
||||||
opt(
|
opt(
|
||||||
'tab_title_template',
|
'tab_title_template',
|
||||||
'"{fmt.fg.red}{bell_symbol}{activity_symbol}{exit_status_symbol}{secure_input_symbol}{fmt.fg.tab}{tab.last_focused_progress_percent}{tab.active_wd_abbreviated} {title}"',
|
'"{fmt.fg.red}{bell_symbol}{activity_symbol}{exit_status_symbol}{secure_input_symbol}{fmt.fg.tab}{tab.last_focused_progress_percent}{title}"',
|
||||||
option_type='tab_title_template',
|
option_type='tab_title_template',
|
||||||
long_text="""
|
long_text="""
|
||||||
A template to render the tab title. The default just renders the title with
|
A template to render the tab title. The default just renders the title with
|
||||||
@@ -3355,14 +3355,11 @@ first valid match, in the order specified, is sourced.
|
|||||||
|
|
||||||
opt(
|
opt(
|
||||||
'notify_on_cmd_finish',
|
'notify_on_cmd_finish',
|
||||||
'unfocused',
|
'never',
|
||||||
option_type='notify_on_cmd_finish',
|
option_type='notify_on_cmd_finish',
|
||||||
long_text="""
|
long_text="""
|
||||||
Show a desktop notification when a long-running command finishes
|
Show a desktop notification when a long-running command finishes
|
||||||
(needs :opt:`shell_integration`).
|
(needs :opt:`shell_integration`).
|
||||||
The notification gives the command line, how long it ran and its exit status.
|
|
||||||
By default commands running longer than 5 seconds are reported when the window
|
|
||||||
loses focus, set the value to :code:`never` to disable this.
|
|
||||||
The possible values are:
|
The possible values are:
|
||||||
|
|
||||||
:code:`never`
|
:code:`never`
|
||||||
@@ -3959,15 +3956,6 @@ map(
|
|||||||
'paste_from_selection shift+insert paste_from_selection',
|
'paste_from_selection shift+insert paste_from_selection',
|
||||||
)
|
)
|
||||||
|
|
||||||
map(
|
|
||||||
'Paste from clipboard history',
|
|
||||||
'paste_from_clipboard_history --allow-fallback=shifted,ascii kitty_mod+alt+v paste_from_clipboard_history',
|
|
||||||
)
|
|
||||||
map(
|
|
||||||
'Search the clipboard history',
|
|
||||||
'search_clipboard_history --allow-fallback=shifted,ascii kitty_mod+alt+f search_clipboard_history',
|
|
||||||
)
|
|
||||||
|
|
||||||
map(
|
map(
|
||||||
'Pass selection to program',
|
'Pass selection to program',
|
||||||
'pass_selection_to_program --allow-fallback=shifted,ascii kitty_mod+o pass_selection_to_program',
|
'pass_selection_to_program --allow-fallback=shifted,ascii kitty_mod+o pass_selection_to_program',
|
||||||
@@ -4661,23 +4649,6 @@ shortcuts. For a full description see :doc:`hints kitten </kittens/hints>`.
|
|||||||
""") # }}}
|
""") # }}}
|
||||||
|
|
||||||
|
|
||||||
# shortcuts.session {{{
|
|
||||||
agr('shortcuts.session', 'Sessions')
|
|
||||||
|
|
||||||
map(
|
|
||||||
'Restore the last session',
|
|
||||||
'restore_last_session --allow-fallback=shifted,ascii kitty_mod+alt+r restore_last_session',
|
|
||||||
long_text="""
|
|
||||||
Restores the tabs, windows, layouts and working directories of the session that
|
|
||||||
was saved when kitty last quit, without restarting kitty. The state is written
|
|
||||||
by :code:`quit`; see :ref:`sessions`. If there is nothing to restore, a bell is
|
|
||||||
rung instead.
|
|
||||||
""",
|
|
||||||
)
|
|
||||||
|
|
||||||
egr() # }}}
|
|
||||||
|
|
||||||
|
|
||||||
# shortcuts.misc {{{
|
# shortcuts.misc {{{
|
||||||
agr('shortcuts.misc', 'Miscellaneous')
|
agr('shortcuts.misc', 'Miscellaneous')
|
||||||
|
|
||||||
@@ -4685,25 +4656,6 @@ map('Show documentation', 'show_kitty_doc kitty_mod+f1 show_kitty_doc overview')
|
|||||||
|
|
||||||
map('Command palette', 'command_palette kitty_mod+f3 command_palette')
|
map('Command palette', 'command_palette kitty_mod+f3 command_palette')
|
||||||
|
|
||||||
map(
|
|
||||||
'Keyboard shortcuts',
|
|
||||||
'keyboard_shortcuts kitty_mod+h launch --type=window-dock --dock-edge=left --dock-size=60 kitty +kitten help',
|
|
||||||
long_text="""
|
|
||||||
Open the searchable keyboard shortcuts panel in a dock at the left edge of the
|
|
||||||
current window. It can also be launched manually with :code:`kitty +kitten help`.
|
|
||||||
The default binding is :kbd:`kitty_mod+h` (:kbd:`Ctrl+Shift+H` by default).
|
|
||||||
""",
|
|
||||||
)
|
|
||||||
|
|
||||||
map(
|
|
||||||
'File manager',
|
|
||||||
'file_manager ctrl+shift+e launch --type=window-dock --dock-edge=left --dock-size=60 kitten file-manager',
|
|
||||||
long_text="""
|
|
||||||
Open the built-in file manager in a dock at the left edge of the current window.
|
|
||||||
It can also be launched manually with :code:`kitten file-manager`.
|
|
||||||
""",
|
|
||||||
)
|
|
||||||
|
|
||||||
map(
|
map(
|
||||||
'Toggle fullscreen',
|
'Toggle fullscreen',
|
||||||
'toggle_fullscreen kitty_mod+f11 toggle_fullscreen',
|
'toggle_fullscreen kitty_mod+f11 toggle_fullscreen',
|
||||||
|
|||||||
Generated
-1
@@ -4,7 +4,6 @@
|
|||||||
#include "to-c.h"
|
#include "to-c.h"
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
static void
|
static void
|
||||||
convert_from_python_font_size(PyObject *val, Options *opts) {
|
convert_from_python_font_size(PyObject *val, Options *opts) {
|
||||||
opts->font_size = PyFloat_AsDouble(val);
|
opts->font_size = PyFloat_AsDouble(val);
|
||||||
|
|||||||
Generated
+2
-12
@@ -640,7 +640,7 @@ class Options:
|
|||||||
mark3_foreground: Color = Color(0, 0, 0)
|
mark3_foreground: Color = Color(0, 0, 0)
|
||||||
momentum_scroll: float = 0.96
|
momentum_scroll: float = 0.96
|
||||||
mouse_hide_wait: MouseHideWait = MouseHideWait(hide_wait=0.0, show_wait=0.0, show_threshold=40, scroll_show=True) if is_macos else MouseHideWait(hide_wait=3.0, show_wait=0.0, show_threshold=40, scroll_show=True)
|
mouse_hide_wait: MouseHideWait = MouseHideWait(hide_wait=0.0, show_wait=0.0, show_threshold=40, scroll_show=True) if is_macos else MouseHideWait(hide_wait=3.0, show_wait=0.0, show_threshold=40, scroll_show=True)
|
||||||
notify_on_cmd_finish: NotifyOnCmdFinish = NotifyOnCmdFinish(when='unfocused', duration=5.0, action='notify', cmdline=(), clear_on=('focus', 'next'))
|
notify_on_cmd_finish: NotifyOnCmdFinish = NotifyOnCmdFinish(when='never', duration=5.0, action='notify', cmdline=(), clear_on=('focus', 'next'))
|
||||||
open_url_with: list[str] = ['default']
|
open_url_with: list[str] = ['default']
|
||||||
padding_fill_strategy: choices_for_padding_fill_strategy = 'background'
|
padding_fill_strategy: choices_for_padding_fill_strategy = 'background'
|
||||||
palette_generate: choices_for_palette_generate = 'fixed'
|
palette_generate: choices_for_palette_generate = 'fixed'
|
||||||
@@ -704,7 +704,7 @@ class Options:
|
|||||||
tab_switch_strategy: choices_for_tab_switch_strategy = 'previous'
|
tab_switch_strategy: choices_for_tab_switch_strategy = 'previous'
|
||||||
tab_title_max_length: int = 0
|
tab_title_max_length: int = 0
|
||||||
tab_title_max_lines: int = 1
|
tab_title_max_lines: int = 1
|
||||||
tab_title_template: str = '{fmt.fg.red}{bell_symbol}{activity_symbol}{exit_status_symbol}{secure_input_symbol}{fmt.fg.tab}{tab.last_focused_progress_percent}{tab.active_wd_abbreviated} {title}'
|
tab_title_template: str = '{fmt.fg.red}{bell_symbol}{activity_symbol}{exit_status_symbol}{secure_input_symbol}{fmt.fg.tab}{tab.last_focused_progress_percent}{title}'
|
||||||
tab_title_wrap: int = 0
|
tab_title_wrap: int = 0
|
||||||
term: str = 'xterm-kitty'
|
term: str = 'xterm-kitty'
|
||||||
terminfo_type: choices_for_terminfo_type = 'path'
|
terminfo_type: choices_for_terminfo_type = 'path'
|
||||||
@@ -902,10 +902,6 @@ defaults.map = [
|
|||||||
KeyDefinition(trigger=SingleKey(mods=256, key=115), options=KeyMapOptions(when_focus_on='', new_mode='', mode='', on_unknown='beep', on_action='keep', timeout=None, allow_fallback=(KeyFallbackType.shifted, KeyFallbackType.alternate)), definition='paste_from_selection'),
|
KeyDefinition(trigger=SingleKey(mods=256, key=115), options=KeyMapOptions(when_focus_on='', new_mode='', mode='', on_unknown='beep', on_action='keep', timeout=None, allow_fallback=(KeyFallbackType.shifted, KeyFallbackType.alternate)), definition='paste_from_selection'),
|
||||||
# paste_from_selection
|
# paste_from_selection
|
||||||
KeyDefinition(trigger=SingleKey(mods=1, key=57348), definition='paste_from_selection'),
|
KeyDefinition(trigger=SingleKey(mods=1, key=57348), definition='paste_from_selection'),
|
||||||
# paste_from_clipboard_history
|
|
||||||
KeyDefinition(trigger=SingleKey(mods=258, key=118), options=KeyMapOptions(when_focus_on='', new_mode='', mode='', on_unknown='beep', on_action='keep', timeout=None, allow_fallback=(KeyFallbackType.shifted, KeyFallbackType.alternate)), definition='paste_from_clipboard_history'),
|
|
||||||
# search_clipboard_history
|
|
||||||
KeyDefinition(trigger=SingleKey(mods=258, key=102), options=KeyMapOptions(when_focus_on='', new_mode='', mode='', on_unknown='beep', on_action='keep', timeout=None, allow_fallback=(KeyFallbackType.shifted, KeyFallbackType.alternate)), definition='search_clipboard_history'),
|
|
||||||
# pass_selection_to_program
|
# pass_selection_to_program
|
||||||
KeyDefinition(trigger=SingleKey(mods=256, key=111), options=KeyMapOptions(when_focus_on='', new_mode='', mode='', on_unknown='beep', on_action='keep', timeout=None, allow_fallback=(KeyFallbackType.shifted, KeyFallbackType.alternate)), definition='pass_selection_to_program'),
|
KeyDefinition(trigger=SingleKey(mods=256, key=111), options=KeyMapOptions(when_focus_on='', new_mode='', mode='', on_unknown='beep', on_action='keep', timeout=None, allow_fallback=(KeyFallbackType.shifted, KeyFallbackType.alternate)), definition='pass_selection_to_program'),
|
||||||
# scroll_line_up
|
# scroll_line_up
|
||||||
@@ -1028,16 +1024,10 @@ defaults.map = [
|
|||||||
KeyDefinition(is_sequence=True, trigger=SingleKey(mods=256, key=112), rest=(SingleKey(key=110),), options=KeyMapOptions(when_focus_on='', new_mode='', mode='', on_unknown='beep', on_action='keep', timeout=None, allow_fallback=(KeyFallbackType.shifted, KeyFallbackType.alternate)), definition='kitten hints --type linenum'),
|
KeyDefinition(is_sequence=True, trigger=SingleKey(mods=256, key=112), rest=(SingleKey(key=110),), options=KeyMapOptions(when_focus_on='', new_mode='', mode='', on_unknown='beep', on_action='keep', timeout=None, allow_fallback=(KeyFallbackType.shifted, KeyFallbackType.alternate)), definition='kitten hints --type linenum'),
|
||||||
# open_selected_hyperlink
|
# open_selected_hyperlink
|
||||||
KeyDefinition(is_sequence=True, trigger=SingleKey(mods=256, key=112), rest=(SingleKey(key=121),), options=KeyMapOptions(when_focus_on='', new_mode='', mode='', on_unknown='beep', on_action='keep', timeout=None, allow_fallback=(KeyFallbackType.shifted, KeyFallbackType.alternate)), definition='kitten hints --type hyperlink'),
|
KeyDefinition(is_sequence=True, trigger=SingleKey(mods=256, key=112), rest=(SingleKey(key=121),), options=KeyMapOptions(when_focus_on='', new_mode='', mode='', on_unknown='beep', on_action='keep', timeout=None, allow_fallback=(KeyFallbackType.shifted, KeyFallbackType.alternate)), definition='kitten hints --type hyperlink'),
|
||||||
# restore_last_session
|
|
||||||
KeyDefinition(trigger=SingleKey(mods=258, key=114), options=KeyMapOptions(when_focus_on='', new_mode='', mode='', on_unknown='beep', on_action='keep', timeout=None, allow_fallback=(KeyFallbackType.shifted, KeyFallbackType.alternate)), definition='restore_last_session'),
|
|
||||||
# show_kitty_doc
|
# show_kitty_doc
|
||||||
KeyDefinition(trigger=SingleKey(mods=256, key=57364), definition='show_kitty_doc overview'),
|
KeyDefinition(trigger=SingleKey(mods=256, key=57364), definition='show_kitty_doc overview'),
|
||||||
# command_palette
|
# command_palette
|
||||||
KeyDefinition(trigger=SingleKey(mods=256, key=57366), definition='command_palette'),
|
KeyDefinition(trigger=SingleKey(mods=256, key=57366), definition='command_palette'),
|
||||||
# file_manager
|
|
||||||
KeyDefinition(trigger=SingleKey(mods=5, key=101), definition='launch --type=window-dock --dock-edge=left --dock-size=60 kitten file-manager'),
|
|
||||||
# keyboard_shortcuts
|
|
||||||
KeyDefinition(trigger=SingleKey(mods=5, key=104), definition='launch --type=window-dock --dock-edge=left --dock-size=60 kitty +kitten help'),
|
|
||||||
# toggle_fullscreen
|
# toggle_fullscreen
|
||||||
KeyDefinition(trigger=SingleKey(mods=256, key=57374), definition='toggle_fullscreen'),
|
KeyDefinition(trigger=SingleKey(mods=256, key=57374), definition='toggle_fullscreen'),
|
||||||
# toggle_maximized
|
# toggle_maximized
|
||||||
|
|||||||
+1
-9
@@ -327,15 +327,7 @@ def create_sessions(
|
|||||||
env_when_no_session: dict[str, str] | None = None,
|
env_when_no_session: dict[str, str] | None = None,
|
||||||
) -> Iterator[Session]:
|
) -> Iterator[Session]:
|
||||||
if args and args.session:
|
if args and args.session:
|
||||||
if args.session == 'last':
|
if args.session == 'none':
|
||||||
from .session_restore import load_last_session, state_path
|
|
||||||
|
|
||||||
raw = load_last_session()
|
|
||||||
if raw:
|
|
||||||
yield from parse_session(raw, opts, session_arg='last', session_path=state_path())
|
|
||||||
return
|
|
||||||
log_error('There is no saved session to restore, starting a new session instead')
|
|
||||||
elif args.session == 'none':
|
|
||||||
default_session = 'none'
|
default_session = 'none'
|
||||||
else:
|
else:
|
||||||
session_arg = args.session
|
session_arg = args.session
|
||||||
|
|||||||
@@ -1,162 +0,0 @@
|
|||||||
#!/usr/bin/env python
|
|
||||||
# License: GPL v3 Copyright: 2026, Kovid Goyal <kovid at kovidgoyal.net>
|
|
||||||
|
|
||||||
# Keep the state of the session that was last in use so that `kitty --session=last` can restore it.
|
|
||||||
#
|
|
||||||
# The state is stored in the XDG state directory, is bounded in size and is only ever read when the
|
|
||||||
# user explicitly asks for it, since restoring an unexpected state is worse than not restoring
|
|
||||||
# anything. Anything that cannot be read back is discarded instead of preventing startup.
|
|
||||||
|
|
||||||
import json
|
|
||||||
import os
|
|
||||||
import time
|
|
||||||
from contextlib import suppress
|
|
||||||
from typing import TYPE_CHECKING, Any
|
|
||||||
|
|
||||||
from .config import atomic_save
|
|
||||||
from .utils import log_error
|
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
|
||||||
from .typing_compat import BossType
|
|
||||||
|
|
||||||
STATE_VERSION = 1
|
|
||||||
MAX_STATE_SIZE = 1024 * 1024
|
|
||||||
STATE_FILE_NAME = 'last-session.json'
|
|
||||||
|
|
||||||
|
|
||||||
def state_dir() -> str:
|
|
||||||
base = os.environ.get('XDG_STATE_HOME') or os.path.join(os.path.expanduser('~'), '.local', 'state')
|
|
||||||
return os.path.join(base, 'kitty')
|
|
||||||
|
|
||||||
|
|
||||||
def state_path() -> str:
|
|
||||||
return os.path.join(state_dir(), STATE_FILE_NAME)
|
|
||||||
|
|
||||||
|
|
||||||
def serialize_state(session: str, saved_at: float | None = None) -> bytes:
|
|
||||||
state = {'version': STATE_VERSION, 'saved_at': time.time() if saved_at is None else saved_at, 'session': session}
|
|
||||||
return json.dumps(state, ensure_ascii=False).encode('utf-8')
|
|
||||||
|
|
||||||
|
|
||||||
def save_last_session(session: str) -> bool:
|
|
||||||
"""Store the session text, returning False when it cannot be stored."""
|
|
||||||
if not session.strip():
|
|
||||||
return False
|
|
||||||
if len(session) > MAX_STATE_SIZE:
|
|
||||||
log_error(f'Not saving the last session as it is larger than {MAX_STATE_SIZE} characters, use save_as_session for large sessions')
|
|
||||||
return False
|
|
||||||
path = state_path()
|
|
||||||
try:
|
|
||||||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
|
||||||
atomic_save(serialize_state(session), path)
|
|
||||||
except OSError as e:
|
|
||||||
log_error(f'Failed to save the last session to {path}: {e}')
|
|
||||||
return False
|
|
||||||
return True
|
|
||||||
|
|
||||||
|
|
||||||
def prune_missing_directories(session: str) -> tuple[str, int]:
|
|
||||||
"""Drop cd directives whose directory is gone, so that a stale state does not fail to restore."""
|
|
||||||
lines: list[str] = []
|
|
||||||
pruned = 0
|
|
||||||
for line in session.splitlines():
|
|
||||||
stripped = line.strip()
|
|
||||||
if stripped.startswith('cd ') and stripped[3:].strip():
|
|
||||||
raw = stripped[3:].strip().strip('"\'')
|
|
||||||
path = os.path.expanduser(raw)
|
|
||||||
if os.path.isabs(path) and not os.path.isdir(path):
|
|
||||||
pruned += 1
|
|
||||||
continue
|
|
||||||
lines.append(line)
|
|
||||||
return '\n'.join(lines), pruned
|
|
||||||
|
|
||||||
|
|
||||||
def discard_last_session() -> None:
|
|
||||||
try:
|
|
||||||
os.remove(state_path())
|
|
||||||
except FileNotFoundError:
|
|
||||||
pass
|
|
||||||
except OSError as e:
|
|
||||||
log_error(f'Failed to delete the unreadable last session: {e}')
|
|
||||||
|
|
||||||
|
|
||||||
def parse_state(raw: bytes) -> str:
|
|
||||||
try:
|
|
||||||
parsed: Any = json.loads(raw)
|
|
||||||
except (ValueError, UnicodeDecodeError) as e:
|
|
||||||
raise ValueError(f'not valid JSON: {e}') from e
|
|
||||||
if not isinstance(parsed, dict):
|
|
||||||
raise ValueError('not a JSON object')
|
|
||||||
version = parsed.get('version')
|
|
||||||
if not isinstance(version, int):
|
|
||||||
raise ValueError('missing state version')
|
|
||||||
if version > STATE_VERSION:
|
|
||||||
raise ValueError(f'state version {version} is newer than the supported version {STATE_VERSION}')
|
|
||||||
session = parsed.get('session')
|
|
||||||
if not isinstance(session, str):
|
|
||||||
raise ValueError('missing session text')
|
|
||||||
return session
|
|
||||||
|
|
||||||
|
|
||||||
def load_last_session() -> str:
|
|
||||||
"""Return the stored session text, or an empty string when there is nothing usable."""
|
|
||||||
path = state_path()
|
|
||||||
try:
|
|
||||||
with open(path, 'rb') as f:
|
|
||||||
raw = f.read(MAX_STATE_SIZE + 1)
|
|
||||||
except FileNotFoundError:
|
|
||||||
return ''
|
|
||||||
except OSError as e:
|
|
||||||
log_error(f'Failed to read the last session from {path}: {e}')
|
|
||||||
return ''
|
|
||||||
if len(raw) > MAX_STATE_SIZE:
|
|
||||||
log_error(f'Discarding the last session in {path} as it is larger than {MAX_STATE_SIZE} bytes')
|
|
||||||
discard_last_session()
|
|
||||||
return ''
|
|
||||||
try:
|
|
||||||
session = parse_state(raw)
|
|
||||||
except ValueError as e:
|
|
||||||
log_error(f'Discarding the last session in {path} as it cannot be read: {e}')
|
|
||||||
discard_last_session()
|
|
||||||
return ''
|
|
||||||
session, pruned = prune_missing_directories(session)
|
|
||||||
if pruned:
|
|
||||||
log_error(f'Dropped {pruned} working directory directive(s) from the last session as the directories no longer exist')
|
|
||||||
return session
|
|
||||||
|
|
||||||
|
|
||||||
def save_session_of(boss: 'BossType') -> None:
|
|
||||||
"""Save the state of a running kitty instance, never raising so that it cannot break quitting."""
|
|
||||||
from .session import default_save_as_session_opts
|
|
||||||
|
|
||||||
try:
|
|
||||||
opts = default_save_as_session_opts()
|
|
||||||
opts.os_window_geometry = True
|
|
||||||
session = '\n'.join(boss.serialize_state_as_session('', opts))
|
|
||||||
save_last_session(session)
|
|
||||||
except Exception as e:
|
|
||||||
log_error(f'Failed to save the last session: {e}')
|
|
||||||
|
|
||||||
|
|
||||||
def restore_last_session_into(boss: 'BossType') -> bool:
|
|
||||||
"""Add the tabs and windows of the last saved session to a running kitty.
|
|
||||||
|
|
||||||
Returns False when there is nothing to restore. The saved state is a JSON document, so it is
|
|
||||||
handed to the session parser through a short lived file rather than duplicating the parsing.
|
|
||||||
"""
|
|
||||||
raw = load_last_session()
|
|
||||||
if not raw:
|
|
||||||
return False
|
|
||||||
import tempfile
|
|
||||||
|
|
||||||
from .session import create_session
|
|
||||||
|
|
||||||
fd, path = tempfile.mkstemp(prefix='last-session-', suffix='.kitty-session')
|
|
||||||
try:
|
|
||||||
with open(fd, 'w', encoding='utf-8') as f:
|
|
||||||
f.write(raw)
|
|
||||||
create_session(boss, path)
|
|
||||||
finally:
|
|
||||||
with suppress(OSError):
|
|
||||||
os.unlink(path)
|
|
||||||
return True
|
|
||||||
@@ -927,17 +927,6 @@ class Tab: # {{{
|
|||||||
restored_scrollback: bytes = b'',
|
restored_scrollback: bytes = b'',
|
||||||
) -> Window:
|
) -> Window:
|
||||||
"Create a new window. When dock is specified, the window is docked to dock_owner or to the tab if dock_owner is None."
|
"Create a new window. When dock is specified, the window is docked to dock_owner or to the tab if dock_owner is None."
|
||||||
# A special window opened over another one, or docked next to it, needs
|
|
||||||
# to know which shell it belongs to: the file manager uses it to find
|
|
||||||
# the session file where that shell publishes its working directory. A
|
|
||||||
# dock follows a window group, so its initial parent is the active
|
|
||||||
# window of the tab it is created in.
|
|
||||||
parent_window_id = overlay_for
|
|
||||||
if parent_window_id is None and dock is not None and (aw := self.active_window) is not None:
|
|
||||||
parent_window_id = aw.id
|
|
||||||
if parent_window_id is not None:
|
|
||||||
env = dict(env or {})
|
|
||||||
env['KITTY_SPECIAL_WINDOW_PARENT'] = str(parent_window_id)
|
|
||||||
cs = WindowCreationSpec(
|
cs = WindowCreationSpec(
|
||||||
use_shell=use_shell,
|
use_shell=use_shell,
|
||||||
cmd=cmd,
|
cmd=cmd,
|
||||||
|
|||||||
+2
-15
@@ -283,19 +283,6 @@ def decode_cmdline(x: str) -> str:
|
|||||||
return ''
|
return ''
|
||||||
|
|
||||||
|
|
||||||
def format_cmd_duration(seconds: float) -> str:
|
|
||||||
"""Human readable duration for the notification sent when a command ends."""
|
|
||||||
if seconds < 1:
|
|
||||||
return f'{seconds * 1000:.0f}ms'
|
|
||||||
if seconds < 60:
|
|
||||||
return f'{seconds:.1f}s'
|
|
||||||
minutes, secs = divmod(int(seconds), 60)
|
|
||||||
if minutes < 60:
|
|
||||||
return f'{minutes}m {secs}s'
|
|
||||||
hours, minutes = divmod(minutes, 60)
|
|
||||||
return f'{hours}h {minutes}m'
|
|
||||||
|
|
||||||
|
|
||||||
class WindowDict(TypedDict):
|
class WindowDict(TypedDict):
|
||||||
id: int
|
id: int
|
||||||
is_focused: bool
|
is_focused: bool
|
||||||
@@ -2089,7 +2076,7 @@ class Window:
|
|||||||
cmd = nm.create_notification_cmd()
|
cmd = nm.create_notification_cmd()
|
||||||
cmd.title = 'kitty'
|
cmd.title = 'kitty'
|
||||||
s = self.last_cmd_cmdline.replace('\\\n', ' ')
|
s = self.last_cmd_cmdline.replace('\\\n', ' ')
|
||||||
cmd.body = f'Command {s} finished in {format_cmd_duration(last_cmd_output_duration)} with status: {self.last_cmd_exit_status}.\nClick to focus.'
|
cmd.body = f'Command {s} finished with status: {exit_status}.\nClick to focus.'
|
||||||
cmd.only_when = OnlyWhen(when)
|
cmd.only_when = OnlyWhen(when)
|
||||||
if not nm.is_notification_allowed(cmd, self.id):
|
if not nm.is_notification_allowed(cmd, self.id):
|
||||||
return
|
return
|
||||||
@@ -2111,7 +2098,7 @@ class Window:
|
|||||||
notify(self, opts, nm)
|
notify(self, opts, nm)
|
||||||
self.screen.bell()
|
self.screen.bell()
|
||||||
elif action == 'command':
|
elif action == 'command':
|
||||||
open_cmd([x.replace('%c', self.last_cmd_cmdline).replace('%s', str(self.last_cmd_exit_status)) for x in notify_cmdline])
|
open_cmd([x.replace('%c', self.last_cmd_cmdline).replace('%s', exit_status) for x in notify_cmdline])
|
||||||
else:
|
else:
|
||||||
raise ValueError(f'Unknown action in option `notify_on_cmd_finish`: {action}')
|
raise ValueError(f'Unknown action in option `notify_on_cmd_finish`: {action}')
|
||||||
|
|
||||||
|
|||||||
@@ -1,133 +0,0 @@
|
|||||||
#!/usr/bin/env python
|
|
||||||
# License: GPL v3 Copyright: 2026, Kovid Goyal <kovid at kovidgoyal.net>
|
|
||||||
|
|
||||||
from kitty.clipboard_history import ClipboardHistory, match_score, text_from_mime_data
|
|
||||||
|
|
||||||
from .base import BaseTest
|
|
||||||
|
|
||||||
|
|
||||||
class TestClipboardHistory(BaseTest):
|
|
||||||
def test_newest_first(self) -> None:
|
|
||||||
h = ClipboardHistory()
|
|
||||||
self.assertFalse(h)
|
|
||||||
self.assertTrue(h.add('one'))
|
|
||||||
self.assertTrue(h.add('two'))
|
|
||||||
self.ae(h.entries(), ('two', 'one'))
|
|
||||||
self.ae(list(h), ['two', 'one'])
|
|
||||||
self.ae(len(h), 2)
|
|
||||||
self.ae(h[0], 'two')
|
|
||||||
|
|
||||||
def test_empty_and_blank_text_is_ignored(self) -> None:
|
|
||||||
h = ClipboardHistory()
|
|
||||||
self.assertFalse(h.add(''))
|
|
||||||
self.assertFalse(h.add(' \n\t'))
|
|
||||||
self.ae(len(h), 0)
|
|
||||||
|
|
||||||
def test_private_entries_are_never_recorded(self) -> None:
|
|
||||||
h = ClipboardHistory()
|
|
||||||
self.assertFalse(h.add('hunter2', private=True))
|
|
||||||
self.ae(len(h), 0)
|
|
||||||
self.assertTrue(h.add('public'))
|
|
||||||
self.assertFalse(h.add('hunter2', private=True))
|
|
||||||
self.ae(h.entries(), ('public',))
|
|
||||||
|
|
||||||
def test_duplicates_move_to_the_top(self) -> None:
|
|
||||||
h = ClipboardHistory()
|
|
||||||
for x in ('a', 'b', 'a'):
|
|
||||||
h.add(x)
|
|
||||||
self.ae(h.entries(), ('a', 'b'))
|
|
||||||
|
|
||||||
def test_entry_count_is_bounded(self) -> None:
|
|
||||||
h = ClipboardHistory(max_entries=3)
|
|
||||||
for x in ('a', 'b', 'c', 'd', 'e'):
|
|
||||||
h.add(x)
|
|
||||||
self.ae(h.entries(), ('e', 'd', 'c'))
|
|
||||||
|
|
||||||
def test_total_size_is_bounded(self) -> None:
|
|
||||||
h = ClipboardHistory(max_entries=100, max_total_chars=10)
|
|
||||||
h.add('12345')
|
|
||||||
h.add('67890')
|
|
||||||
h.add('abcde')
|
|
||||||
self.assertLessEqual(sum(len(x) for x in h.entries()), 10)
|
|
||||||
self.ae(h.entries()[0], 'abcde')
|
|
||||||
|
|
||||||
def test_oversized_entries_are_ignored(self) -> None:
|
|
||||||
h = ClipboardHistory(max_entry_chars=5)
|
|
||||||
self.assertFalse(h.add('123456'))
|
|
||||||
self.assertTrue(h.add('12345'))
|
|
||||||
self.ae(h.entries(), ('12345',))
|
|
||||||
|
|
||||||
def test_clear(self) -> None:
|
|
||||||
h = ClipboardHistory()
|
|
||||||
h.add('a')
|
|
||||||
h.clear()
|
|
||||||
self.ae(len(h), 0)
|
|
||||||
self.assertFalse(h)
|
|
||||||
# clearing resets the accounting, so new entries are kept even after large ones
|
|
||||||
self.assertTrue(h.add('b'))
|
|
||||||
self.ae(h.entries(), ('b',))
|
|
||||||
|
|
||||||
def test_search(self) -> None:
|
|
||||||
h = ClipboardHistory()
|
|
||||||
for x in ('make test', 'make build', 'git status', 'echo make'):
|
|
||||||
h.add(x)
|
|
||||||
self.ae(h.search(''), h.entries())
|
|
||||||
self.ae(h.search(' '), h.entries())
|
|
||||||
# An earlier substring match ranks first, ties keep the newest entry first
|
|
||||||
self.ae(h.search('make'), ('make build', 'make test', 'echo make'))
|
|
||||||
self.ae(h.search('mkb'), ('make build',))
|
|
||||||
self.ae(h.search('zzz'), ())
|
|
||||||
|
|
||||||
def test_substring_matches_rank_before_subsequences(self) -> None:
|
|
||||||
h = ClipboardHistory()
|
|
||||||
h.add('xkcd')
|
|
||||||
h.add('kcd')
|
|
||||||
self.ae(h.search('kcd'), ('kcd', 'xkcd'))
|
|
||||||
|
|
||||||
def test_match_score(self) -> None:
|
|
||||||
self.ae(match_score('', 'anything'), 0)
|
|
||||||
self.ae(match_score('abc', 'xxabc'), 2)
|
|
||||||
self.assertGreater(match_score('abc', 'a-x-b-x-c'), 2)
|
|
||||||
self.ae(match_score('abc', 'cba'), -1)
|
|
||||||
self.ae(match_score('Abc', 'xxabc'), 2) # matching is case insensitive
|
|
||||||
|
|
||||||
def test_text_from_bytes(self) -> None:
|
|
||||||
self.ae(text_from_mime_data(b'hello'), 'hello')
|
|
||||||
self.ae(text_from_mime_data('not bytes'), '')
|
|
||||||
self.ae(text_from_mime_data(None), '')
|
|
||||||
self.ae(text_from_mime_data(b'a\xffb'), 'a\ufffdb')
|
|
||||||
|
|
||||||
def test_text_from_chunker(self) -> None:
|
|
||||||
# OSC 52 writes are streamed, so the clipboard stores a chunker factory not bytes
|
|
||||||
chunks = [b'first ', b'second', b'']
|
|
||||||
|
|
||||||
def factory():
|
|
||||||
it = iter(chunks)
|
|
||||||
|
|
||||||
def chunker():
|
|
||||||
return next(it, b'')
|
|
||||||
|
|
||||||
return chunker
|
|
||||||
|
|
||||||
self.ae(text_from_mime_data(factory), 'first second')
|
|
||||||
|
|
||||||
def test_text_from_chunker_is_bounded(self) -> None:
|
|
||||||
def factory():
|
|
||||||
remaining = [b'x' * 1000] * 1000
|
|
||||||
it = iter(remaining)
|
|
||||||
|
|
||||||
def chunker():
|
|
||||||
return next(it, b'')
|
|
||||||
|
|
||||||
return chunker
|
|
||||||
|
|
||||||
ans = text_from_mime_data(factory, max_chars=10)
|
|
||||||
self.assertLessEqual(len(ans), 40)
|
|
||||||
self.assertTrue(ans)
|
|
||||||
|
|
||||||
def test_no_persistence_api(self) -> None:
|
|
||||||
# The history is deliberately memory only: there is no save/load entry point to call
|
|
||||||
h = ClipboardHistory()
|
|
||||||
self.assertFalse(hasattr(h, 'save'))
|
|
||||||
self.assertFalse(hasattr(h, 'load'))
|
|
||||||
self.assertFalse(hasattr(h, 'path'))
|
|
||||||
@@ -364,18 +364,6 @@ class TestNotifications(BaseTest):
|
|||||||
with tempfile.TemporaryDirectory() as tdir:
|
with tempfile.TemporaryDirectory() as tdir:
|
||||||
do_test(self, tdir)
|
do_test(self, tdir)
|
||||||
|
|
||||||
def test_command_finish_duration_formatting(self):
|
|
||||||
from kitty.window import format_cmd_duration
|
|
||||||
|
|
||||||
self.ae(format_cmd_duration(0), '0ms')
|
|
||||||
self.ae(format_cmd_duration(0.42), '420ms')
|
|
||||||
self.ae(format_cmd_duration(1.0), '1.0s')
|
|
||||||
self.ae(format_cmd_duration(59.94), '59.9s')
|
|
||||||
self.ae(format_cmd_duration(60), '1m 0s')
|
|
||||||
self.ae(format_cmd_duration(3599), '59m 59s')
|
|
||||||
self.ae(format_cmd_duration(3600), '1h 0m')
|
|
||||||
self.ae(format_cmd_duration(7325), '2h 2m')
|
|
||||||
|
|
||||||
def test_freedesktop_close_before_created(self):
|
def test_freedesktop_close_before_created(self):
|
||||||
import kitty.fast_data_types as fdt
|
import kitty.fast_data_types as fdt
|
||||||
|
|
||||||
|
|||||||
@@ -1,145 +0,0 @@
|
|||||||
#!/usr/bin/env python
|
|
||||||
# License: GPL v3 Copyright: 2026, Kovid Goyal <kovid at kovidgoyal.net>
|
|
||||||
|
|
||||||
import json
|
|
||||||
import os
|
|
||||||
import shutil
|
|
||||||
import tempfile
|
|
||||||
from unittest.mock import patch
|
|
||||||
|
|
||||||
from kitty.config import load_config
|
|
||||||
from kitty.session import create_sessions, parse_session
|
|
||||||
from kitty.session_restore import (
|
|
||||||
MAX_STATE_SIZE,
|
|
||||||
discard_last_session,
|
|
||||||
load_last_session,
|
|
||||||
prune_missing_directories,
|
|
||||||
save_last_session,
|
|
||||||
state_path,
|
|
||||||
)
|
|
||||||
from kitty.utils import log_error
|
|
||||||
|
|
||||||
from .base import BaseTest
|
|
||||||
|
|
||||||
|
|
||||||
class TestSessionRestore(BaseTest):
|
|
||||||
def setUp(self) -> None:
|
|
||||||
super().setUp()
|
|
||||||
self.tdir = tempfile.mkdtemp()
|
|
||||||
self.env_patch = patch.dict(os.environ, {'XDG_STATE_HOME': self.tdir})
|
|
||||||
self.env_patch.start()
|
|
||||||
self.error_messages: list[str] = []
|
|
||||||
log_error.redirect = self.error_messages.append
|
|
||||||
|
|
||||||
def tearDown(self) -> None:
|
|
||||||
del log_error.redirect
|
|
||||||
self.env_patch.stop()
|
|
||||||
shutil.rmtree(self.tdir)
|
|
||||||
super().tearDown()
|
|
||||||
|
|
||||||
def write_state(self, data: bytes) -> None:
|
|
||||||
os.makedirs(os.path.dirname(state_path()), exist_ok=True)
|
|
||||||
with open(state_path(), 'wb') as f:
|
|
||||||
f.write(data)
|
|
||||||
|
|
||||||
def test_state_lives_in_the_xdg_state_directory(self) -> None:
|
|
||||||
self.ae(state_path(), os.path.join(self.tdir, 'kitty', 'last-session.json'))
|
|
||||||
|
|
||||||
def test_roundtrip(self) -> None:
|
|
||||||
session = 'new_tab work\nlayout tall\ncd /tmp\nlaunch --title editor\nlaunch'
|
|
||||||
self.assertTrue(save_last_session(session))
|
|
||||||
self.assertTrue(os.path.exists(state_path()))
|
|
||||||
self.ae(load_last_session(), session)
|
|
||||||
|
|
||||||
def test_nothing_is_saved_for_an_empty_session(self) -> None:
|
|
||||||
self.assertFalse(save_last_session(' \n'))
|
|
||||||
self.ae(load_last_session(), '')
|
|
||||||
|
|
||||||
def test_missing_state_is_not_an_error(self) -> None:
|
|
||||||
self.ae(load_last_session(), '')
|
|
||||||
self.ae(self.error_messages, [])
|
|
||||||
|
|
||||||
def test_too_large_state_is_neither_saved_nor_restored(self) -> None:
|
|
||||||
self.assertFalse(save_last_session('x' * (MAX_STATE_SIZE + 1)))
|
|
||||||
self.assertFalse(os.path.exists(state_path()))
|
|
||||||
self.write_state(json.dumps({'version': 1, 'session': 'x' * (MAX_STATE_SIZE + 1)}).encode())
|
|
||||||
self.ae(load_last_session(), '')
|
|
||||||
self.assertFalse(os.path.exists(state_path()))
|
|
||||||
self.assertTrue(self.error_messages)
|
|
||||||
|
|
||||||
def test_corrupt_state_is_discarded(self) -> None:
|
|
||||||
self.write_state(b'{"version": 1, "session": ')
|
|
||||||
self.ae(load_last_session(), '')
|
|
||||||
self.assertFalse(os.path.exists(state_path()))
|
|
||||||
self.assertTrue(any('cannot be read' in msg for msg in self.error_messages))
|
|
||||||
|
|
||||||
def test_newer_state_version_is_discarded(self) -> None:
|
|
||||||
self.write_state(json.dumps({'version': 99, 'session': 'launch'}).encode())
|
|
||||||
self.ae(load_last_session(), '')
|
|
||||||
self.assertFalse(os.path.exists(state_path()))
|
|
||||||
|
|
||||||
def test_missing_or_invalid_fields_are_discarded(self) -> None:
|
|
||||||
for data in ({}, {'version': 1}, {'session': 'launch'}, {'version': '1', 'session': 'launch'}, []):
|
|
||||||
self.write_state(json.dumps(data).encode())
|
|
||||||
self.ae(load_last_session(), '', data)
|
|
||||||
self.assertFalse(os.path.exists(state_path()), data)
|
|
||||||
self.assertFalse(os.path.exists(state_path()))
|
|
||||||
|
|
||||||
def test_discard_is_idempotent(self) -> None:
|
|
||||||
discard_last_session()
|
|
||||||
self.ae(self.error_messages, [])
|
|
||||||
|
|
||||||
def test_stale_directories_are_pruned(self) -> None:
|
|
||||||
missing = os.path.join(self.tdir, 'gone')
|
|
||||||
session = f'new_tab a\ncd {missing}\nlaunch\nnew_tab b\ncd {self.tdir}\nlaunch'
|
|
||||||
session, pruned = prune_missing_directories(session)
|
|
||||||
self.ae(pruned, 1)
|
|
||||||
self.assertNotIn(missing, session)
|
|
||||||
self.assertIn(f'cd {self.tdir}', session)
|
|
||||||
self.assertIn('new_tab b', session)
|
|
||||||
self.assertTrue(self.error_messages == []) # pruning itself does not log
|
|
||||||
|
|
||||||
def test_pruning_is_applied_when_loading(self) -> None:
|
|
||||||
missing = os.path.join(self.tdir, 'gone')
|
|
||||||
self.assertTrue(save_last_session(f'cd {missing}\nlaunch'))
|
|
||||||
self.ae(load_last_session(), 'launch')
|
|
||||||
self.assertTrue(any('no longer exist' in msg for msg in self.error_messages))
|
|
||||||
|
|
||||||
def test_saved_state_is_a_valid_session(self) -> None:
|
|
||||||
session = 'new_tab one\nlayout tall\nlaunch\nnew_tab two\nlaunch'
|
|
||||||
self.assertTrue(save_last_session(session))
|
|
||||||
opts = load_config()
|
|
||||||
sessions = tuple(parse_session(load_last_session(), opts, session_arg='last', session_path=state_path()))
|
|
||||||
self.ae(len(sessions), 1)
|
|
||||||
self.ae(sessions[0].session_name, 'last')
|
|
||||||
self.ae([t.name for t in sessions[0].tabs], ['one', 'two'])
|
|
||||||
|
|
||||||
def test_restore_is_explicit_on_the_command_line(self) -> None:
|
|
||||||
from kitty.cli import parse_args
|
|
||||||
|
|
||||||
self.assertTrue(save_last_session('launch'))
|
|
||||||
opts = load_config()
|
|
||||||
args, rest = parse_args(['--session', 'last'])
|
|
||||||
args.args = [] # type: ignore
|
|
||||||
self.ae(args.session, 'last')
|
|
||||||
self.ae(rest, [])
|
|
||||||
sessions = tuple(create_sessions(opts, args))
|
|
||||||
self.ae(len(sessions), 1)
|
|
||||||
self.ae(sessions[0].session_name, 'last')
|
|
||||||
self.ae(len(sessions[0].tabs[0].windows), 1)
|
|
||||||
|
|
||||||
def test_missing_state_falls_back_to_a_fresh_session(self) -> None:
|
|
||||||
from kitty.cli import parse_args
|
|
||||||
|
|
||||||
opts = load_config()
|
|
||||||
args, rest = parse_args(['--session', 'last'])
|
|
||||||
args.args = [] # type: ignore
|
|
||||||
sessions = tuple(create_sessions(opts, args))
|
|
||||||
self.ae(len(sessions), 1)
|
|
||||||
self.ae(sessions[0].session_name, '')
|
|
||||||
self.assertTrue(any('no saved session' in msg for msg in self.error_messages))
|
|
||||||
|
|
||||||
def test_restore_action_without_state_returns_false(self) -> None:
|
|
||||||
from kitty.session_restore import restore_last_session_into
|
|
||||||
|
|
||||||
self.assertFalse(restore_last_session_into(None)) # type: ignore
|
|
||||||
@@ -1,487 +0,0 @@
|
|||||||
# Méthodologie de collaboration Git / GitHub
|
|
||||||
|
|
||||||
**Travail de binôme — document de référence**
|
|
||||||
|
|
||||||
| Élément | Valeur |
|
|
||||||
| --- | --- |
|
|
||||||
| Projet de référence | FWS-Kitty |
|
|
||||||
| Binôme | *Damien Rochat* + *Gianmarco Ruberti* |
|
|
||||||
| Date | Novembre 2026 |
|
|
||||||
| Statut | Version 0.50.0 |
|
|
||||||
|
|
||||||
> Ce document décrit **comment nous travaillerions** sur ce projet dans un contexte professionnel. Aucune manipulation Git réelle n'est effectuée : les commandes et les exemples servent à illustrer concrètement la méthodologie.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 1. Projet de référence
|
|
||||||
|
|
||||||
Le projet retenu comme contexte est **FWS-Kitty**, le fork FWS du terminal kitty, auquel notre équipe ajoute un panneau de gestion de fichiers (`kittens/file_manager/`) : navigation au clavier, création, renommage et suppression d'entrées, changement du répertoire courant du shell, ouverture de fichiers dans l'éditeur.
|
|
||||||
|
|
||||||
Ce projet est représentatif de notre futur quotidien professionnel :
|
|
||||||
|
|
||||||
- **Dépôt volumineux et historique existant** (C, Python, Go, docs Sphinx) : on ne réécrit pas l'existant, on s'y insère.
|
|
||||||
- **Travail en parallèle** sur des zones différentes (interface Go du panneau, options Python, documentation, packaging Arch, CI).
|
|
||||||
- **Un besoin de revue réel** : le code touche au shell de l'utilisateur (suppression de fichiers, `cd`), une erreur coûte cher.
|
|
||||||
- **Des contrôles automatisables** : `./test.py`, `go test ./kittens/file_manager/`, `ruff check`, `./dev.sh build`, `./dev.sh docs`.
|
|
||||||
|
|
||||||
Le choix doit être **validé par l'enseignant avant de poursuivre** (voir tableau ci-dessus, ligne « Projet ETML d'origine »). Si un autre projet est validé, seuls les exemples de commandes changent : la méthodologie reste identique.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 2. Organisation générale (question a)
|
|
||||||
|
|
||||||
### 2.1 Structure d'équipe et rôles
|
|
||||||
|
|
||||||
Nous sommes un binôme, donc chaque rôle est tenu par les deux personnes, mais avec une **responsabilité principale** clairement attribuée pour éviter les zones grises (le « responsable » décide, l'autre relit).
|
|
||||||
|
|
||||||
| Rôle | Responsabilités | Qui |
|
|
||||||
| --- | --- | --- |
|
|
||||||
| **Mainteneur / intégrateur** | Protège `main`, arbitre les désaccords techniques, valide les fusions, tient le `CHANGELOG` et les tags de version | *(binôme A)* |
|
|
||||||
| **Développeur·se / relecteur·se** | Développe les fonctionnalités, relit toutes les PR, vérifie les critères de validation | *(binôme B)* |
|
|
||||||
| **Responsable qualité** | Surveille la CI, le lint, les tests, signale les régressions | Alternance par itération |
|
|
||||||
| **Responsable documentation** | Vérifie que chaque PR met à jour `README.md` / `docs/` | Alternance par itération |
|
|
||||||
|
|
||||||
Les deux membres sont **co-responsables de la relecture** : aucune PR n'est fusionnée sans avoir été lue par l'autre. Règle d'or : *celui qui écrit le code ne valide jamais seul sa propre PR*.
|
|
||||||
|
|
||||||
### 2.2 Répartition du travail
|
|
||||||
|
|
||||||
- Découpage **par fonctionnalité verticale** (de la logique Go jusqu'à la doc), pas par couche technique (sinon tout le monde touche les mêmes fichiers et les conflits explosent).
|
|
||||||
- Une **issue = un périmètre = une branche = une PR**. Si une issue grossit, on la scinde.
|
|
||||||
- Pour le projet de référence : une personne prend « création / renommage / suppression de fichiers », l'autre « changement de répertoire et intégration shell », puis on échange les rôles sur les itérations suivantes pour que chacun connaisse tout le code.
|
|
||||||
|
|
||||||
### 2.3 Communication
|
|
||||||
|
|
||||||
| Canal | Usage | Fréquence |
|
|
||||||
| --- | --- | --- |
|
|
||||||
| **GitHub Issues / PR** | Canal **officiel** : toute décision technique qui compte est écrite ici | Continu |
|
|
||||||
| **GitHub Discussions** | Questions ouvertes, choix d'architecture, sondages | Au besoin |
|
|
||||||
| **Discord (salon privé du binôme)** | Synchronisation rapide, blocages, partage d'écran | Quotidien |
|
|
||||||
| **Visio / point de 15 min** | Point de départ et point de fin de journée : qui fait quoi, qu'est-ce qui bloque | 1 à 2 fois/jour |
|
|
||||||
| **Revue de fin d'itération** | Bilan, reste à faire, mise à jour du Kanban | 1 fois/semaine |
|
|
||||||
|
|
||||||
**Règle de traçabilité de la communication** : une décision prise à l'oral ou sur Discord est **retranscrite dans l'issue ou la PR** concernée avant d'être appliquée. « Si ce n'est pas écrit sur GitHub, ça n'existe pas. » Cela évite les désaccords une semaine plus tard et documente le *pourquoi* des choix.
|
|
||||||
|
|
||||||
### 2.4 Outils complémentaires à GitHub
|
|
||||||
|
|
||||||
| Besoin | Outil retenu | Justification |
|
|
||||||
| --- | --- | --- |
|
|
||||||
| Suivi des tâches | **GitHub Projects** (board Kanban) | Intégré au dépôt : une issue = une carte, aucune double saisie, pas d'outil tiers à administrer |
|
|
||||||
| Communication écrite | GitHub Issues + Discussions, complété par Discord | Le suivi reste sur GitHub, Discord ne sert qu'au temps réel |
|
|
||||||
| Documentation technique | Markdown dans `docs/` (versionné) + `README.md` | La doc évolue dans la même PR que le code |
|
|
||||||
| Intégration continue | **GitHub Actions** | Natif, gratuit sur dépôt public, pas de serveur à maintenir |
|
|
||||||
| Qualité / formatage | `ruff`, `go vet`/`gofmt`, `./test.py`, hooks `pre-commit` | Déjà présents dans le dépôt |
|
|
||||||
| Maquettes / captures | Fichiers versionnés dans `docs/` + commentaire de PR | On garde la trace de l'état avant/après |
|
|
||||||
|
|
||||||
*Alternatives écartées* : Jira et Trello ajoutent un outil et une saisie en double sans apporter de valeur à un binôme ; les tickets vivent déjà dans les issues GitHub, qui sont liées nativement aux commits et aux PR.
|
|
||||||
|
|
||||||
### 2.5 Transparence et suivi des tâches
|
|
||||||
|
|
||||||
1. **Toute demande commence par une issue** (bug, fonctionnalité, tâche technique) avec un gabarit : contexte, résultat attendu, critères d'acceptation, labels.
|
|
||||||
2. **Un board Kanban unique** avec cinq colonnes : `Backlog` → `À faire` → `En cours` (max 1 carte par personne) → `En revue` → `Terminé`.
|
|
||||||
3. **Une seule carte « En cours » par personne** : le travail en cours est visible d'un coup d'œil, on évite le multitâche.
|
|
||||||
4. **Labels normalisés** : `type: feat|fix|docs|chore`, `prio: haute|moyenne|basse`, `zone: go|python|docs|packaging|ci`, `état: bloqué`.
|
|
||||||
5. **Mise à jour en fin de journée** : la carte reflète l'état réel, avec un commentaire de statut si elle stagne.
|
|
||||||
6. **Lien bidirectionnel systématique** : l'issue référence la PR (« Ferme #42 »), la PR référence l'issue, le commit référence l'issue.
|
|
||||||
7. **Journal de décisions** : les choix structurants (workflow, format de fichier de config, découpage) sont consignés dans une issue étiquetée `décision` ou dans un court ADR (`docs/adr/NNN-titre.md`).
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 3. Workflow Git / GitHub (question b)
|
|
||||||
|
|
||||||
### 3.1 Workflow retenu : **GitHub Flow (trunk-based simplifié)**
|
|
||||||
|
|
||||||
Une seule branche longue (`main`, toujours déployable), des branches de travail **courtes** (1 à 3 jours), une Pull Request obligatoire pour intégrer.
|
|
||||||
|
|
||||||
| Critère | GitHub Flow (retenu) | Git Flow | Feature Branch « pur » |
|
|
||||||
| --- | --- | --- | --- |
|
|
||||||
| Complexité | Faible | Élevée (2 branches longues + 3 types) | Faible |
|
|
||||||
| Adapté au binôme | Oui | Non : la `develop` devient un goulot d'étranglement | Oui |
|
|
||||||
| Fréquence d'intégration | Élevée, conflits rares | Faible, gros merges | Moyenne |
|
|
||||||
| Livraisons | Continu, tag sur `main` | Par release planifiée | Au cas par cas |
|
|
||||||
| Historique | Linéaire et lisible | Encombré de merges | Linéaire |
|
|
||||||
|
|
||||||
**Justification du choix** : nous sommes deux, avec des itérations courtes et un besoin de retours rapides. Git Flow a été conçu pour des équipes nombreuses livrant des versions planifiées ; à deux, sa branche `develop` ajoute une étape de synchronisation sans bénéfice. Le Feature Branch « pur » n'impose pas de règle de fusion : il ne protège pas `main`. GitHub Flow combine les avantages : branches courtes (peu de conflits), `main` protégée (qualité), et intégration continue (feedback immédiat).
|
|
||||||
|
|
||||||
### 3.2 Organisation des branches
|
|
||||||
|
|
||||||
| Branche | Rôle | Durée de vie | Protection |
|
|
||||||
| --- | --- | --- | --- |
|
|
||||||
| `main` | Référence unique, **toujours compilable et testée** ; c'est elle qui est empaquetée | Permanente | Protégée : PR obligatoire, 1 approbation, CI verte, pas de push direct, pas de force-push |
|
|
||||||
| `feat/<description>` | Nouvelle fonctionnalité | ≤ 3 jours | Aucune (mais CI obligatoire avant PR) |
|
|
||||||
| `fix/<description>` | Correction de bug (issue existante) | ≤ 1 jour | Aucune |
|
|
||||||
| `docs/<description>` | Documentation seule | ≤ 1 jour | Aucune |
|
|
||||||
| `chore/<description>`, `ci/<description>`, `refactor/<description>` | Maintenance, CI, refonte sans changement de comportement | ≤ 2 jours | Aucune |
|
|
||||||
| `hotfix/<description>` | Correction urgente d'une version livrée | Quelques heures | Part de `main`, fusionnée puis taguée `PATCH` |
|
|
||||||
| `release/x.y.z` | **Uniquement si** une version doit être stabilisée avant livraison | Quelques jours | Créée depuis `main`, sert aux correctifs de dernière minute |
|
|
||||||
|
|
||||||
**Pas de branche `develop`** : `main` joue ce rôle, puisque chaque PR fusionnée est déjà revue et testée.
|
|
||||||
|
|
||||||
**Nommage** (`kebab-case`, en anglais, court et explicite — cohérent avec les conventions du dépôt) :
|
|
||||||
|
|
||||||
```
|
|
||||||
feat/file-manager-panel
|
|
||||||
feat/file-manager-create-entry
|
|
||||||
fix/file-manager-cd-dock
|
|
||||||
docs/file-manager-shortcuts
|
|
||||||
chore/update-dependencies
|
|
||||||
hotfix/version-string
|
|
||||||
```
|
|
||||||
|
|
||||||
Interdits : `ma-branche`, `test`, `wip`, `buffy-2`, les prénoms, les dates, les majuscules et les accents. Une branche doit décrire **l'intention**, pas la personne.
|
|
||||||
|
|
||||||
**Suppression après fusion** : la branche est supprimée automatiquement (option GitHub « Automatically delete head branches ») pour garder un dépôt lisible.
|
|
||||||
|
|
||||||
### 3.3 Cycle complet d'une contribution
|
|
||||||
|
|
||||||
```sh
|
|
||||||
# 1. Se synchroniser
|
|
||||||
git switch main
|
|
||||||
git pull --ff-only
|
|
||||||
|
|
||||||
# 2. Créer la branche de travail (nommée d'après l'issue #42)
|
|
||||||
git switch -c feat/file-manager-create-entry
|
|
||||||
|
|
||||||
# 3. Travailler par petits commits
|
|
||||||
git add kittens/file_manager/main.go
|
|
||||||
git commit -m "feat(file-manager): add file creation from status line"
|
|
||||||
|
|
||||||
# 4. Se resynchroniser régulièrement sur main (évite les gros conflits)
|
|
||||||
git fetch origin
|
|
||||||
git rebase origin/main # branche personnelle uniquement
|
|
||||||
|
|
||||||
# 5. Pousser tôt, pousser souvent
|
|
||||||
git push -u origin feat/file-manager-create-entry
|
|
||||||
|
|
||||||
# 6. Ouvrir une Pull Request (gabarit rempli, CI verte, relecteur assigné)
|
|
||||||
gh pr create --fill --reviewer <binôme>
|
|
||||||
|
|
||||||
# 7. Corriger les retours, puis fusionner en "Squash and merge"
|
|
||||||
git switch main && git pull --ff-only
|
|
||||||
```
|
|
||||||
|
|
||||||
Règles de fusion :
|
|
||||||
|
|
||||||
- **Squash and merge** pour les branches de fonctionnalité : un commit propre par PR dans `main`, l'historique reste lisible et linéaire.
|
|
||||||
- **Merge commit** réservé aux fusions `release/*` / `hotfix/*` pour conserver la trace des deux lignées.
|
|
||||||
- **Rebase and merge** interdit sur `main` : il réécrit les commits déjà revus.
|
|
||||||
|
|
||||||
### 3.4 Protection de `main` (réglages GitHub)
|
|
||||||
|
|
||||||
1. Pull Request obligatoire avant fusion, **aucun push direct** (règle appliquée aussi aux mainteneurs).
|
|
||||||
2. **1 approbation minimum** ; une nouvelle approbation est exigée après chaque push significatif (option « Dismiss stale approvals »).
|
|
||||||
3. **Statuts de CI obligatoires** : `lint`, `tests`, `build`.
|
|
||||||
4. Branche à jour avec `main` avant fusion ; **conversations résolues** obligatoires.
|
|
||||||
5. Force-push et suppression de `main` interdits ; commits **signés** (bonne pratique déjà suivie dans l'organisation FWS).
|
|
||||||
6. `CODEOWNERS` sur `kittens/file_manager/`, `packaging/` et `docs/` : la PR touche ces zones → le relecteur est désigné automatiquement.
|
|
||||||
|
|
||||||
### 3.5 Politique de versionnage : **SemVer 2.0.0**
|
|
||||||
|
|
||||||
Format `MAJEUR.MINEUR.CORRECTIF`, tags Git préfixés `v` :
|
|
||||||
|
|
||||||
| Incrément | Quand | Exemple |
|
|
||||||
| --- | --- | --- |
|
|
||||||
| `MAJEUR` | Changement incompatible (option renommée, comportement cassé, config illisible) | `v1.0.0` |
|
|
||||||
| `MINEUR` | Nouvelle fonctionnalité rétrocompatible (nouvelle action `mkdir`, nouveau raccourci) | `v0.51.0` |
|
|
||||||
| `CORRECTIF` | Correction rétrocompatible (bug, doc erronée d'une option) | `v0.51.1` |
|
|
||||||
|
|
||||||
- Avant la première version stable : `0.y.z`, tout peut bouger, mais on reste rigoureux sur `z`.
|
|
||||||
- Pré-versions : `v0.51.0-rc.1` (release candidate), `v0.51.1-beta.2`.
|
|
||||||
- **Tag annoté et signé** sur `main`, jamais sur une branche de travail :
|
|
||||||
```sh
|
|
||||||
git tag -s v0.51.0 -m "file-manager: create, rename, delete entries"
|
|
||||||
git push origin v0.51.0
|
|
||||||
```
|
|
||||||
- **`CHANGELOG.md` mis à jour dans la PR de release** (sections `Ajouté`, `Modifié`, `Corrigé`, `Supprimé`, `Sécurité`), et **release GitHub** créée depuis le tag avec les notes correspondantes.
|
|
||||||
- Une version livrée ne se modifie jamais : on publie un `CORRECTIF`, on ne réécrit pas un tag existant.
|
|
||||||
|
|
||||||
### 3.6 Convention de commits : **Conventional Commits 1.0.0**
|
|
||||||
|
|
||||||
Format : `<type>(<portée>): <description impérative>`, **en anglais**, titre ≤ 72 caractères, corps optionnel expliquant le *pourquoi*.
|
|
||||||
|
|
||||||
| Type | Usage |
|
|
||||||
| --- | --- |
|
|
||||||
| `feat` | Nouvelle fonctionnalité visible par l'utilisateur |
|
|
||||||
| `fix` | Correction de bug |
|
|
||||||
| `docs` | Documentation uniquement |
|
|
||||||
| `style` | Formatage, espaces (aucun changement de comportement) |
|
|
||||||
| `refactor` | Réécriture interne sans changement de comportement |
|
|
||||||
| `perf` | Amélioration de performance |
|
|
||||||
| `test` | Ajout ou correction de tests |
|
|
||||||
| `build` | Système de build, dépendances, packaging |
|
|
||||||
| `ci` | Configuration de l'intégration continue |
|
|
||||||
| `chore` | Tâches annexes (`.gitignore`, scripts) |
|
|
||||||
| `revert` | Annulation d'un commit précédent |
|
|
||||||
|
|
||||||
Exemples conformes :
|
|
||||||
|
|
||||||
```
|
|
||||||
feat(file-manager): add directory creation with shift+n
|
|
||||||
fix(file-manager): keep cd working when panel runs in a dock
|
|
||||||
docs(file-manager): document default key bindings
|
|
||||||
refactor(file-manager): extract path formatting into a helper
|
|
||||||
test(file-manager): cover truncateToWidth with wide characters
|
|
||||||
ci: run go tests for the file manager kitten
|
|
||||||
```
|
|
||||||
|
|
||||||
Règles complémentaires :
|
|
||||||
|
|
||||||
- **Un commit = un changement cohérent** qui compile et dont les tests passent.
|
|
||||||
- **Impératif présent** (« add », pas « added » ni « adds ») : le commit décrit ce qu'il fait.
|
|
||||||
- **Pas de commits fourre-tout** (`wip`, `fix stuff`, `update`) : ils sont écrasés par le squash avant fusion, mais polluent la relecture.
|
|
||||||
- **Référence à l'issue** dans le corps ou le pied : `Refs #42`, `Fixes #42`, `Closes #42` (fermeture automatique).
|
|
||||||
- **Breaking change** : `feat(config)!: rename sort_by values` + pied `BREAKING CHANGE: …` → déclenche un `MAJEUR` (ou `0.y` incrémenté).
|
|
||||||
- Gabarit local (`.gitmessage`) et hook `commit-msg` (Commitlint) pour vérifier le format avant même le push.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 4. Processus de revue de code (question c)
|
|
||||||
|
|
||||||
### 4.1 Déroulement d'une Pull Request
|
|
||||||
|
|
||||||
1. **Ouverture précoce en brouillon** (`Draft PR`) dès le premier commit poussé : la CI tourne, l'autre peut suivre l'avancement. Aucune revue formelle demandée tant qu'elle est en brouillon.
|
|
||||||
2. **PR prête** : description remplie grâce au gabarit (contexte, issue liée, ce qui a changé, comment tester, captures si l'affichage change), relecteur assigné, labels posés.
|
|
||||||
3. **CI** : `lint` + `tests` + `build` doivent être verts. Une PR rouge n'est **pas relue en profondeur** : l'auteur corrige d'abord.
|
|
||||||
4. **Revue** par l'autre membre, sous **24 h ouvrées** (objectif : quelques heures). Trois verdicts possibles : *Approve*, *Request changes* (bloquant, avec justification), *Comment* (non bloquant).
|
|
||||||
5. **Corrections** par l'auteur, en commits supplémentaires (pas de force-push pendant la revue, pour que le relecteur voie le diff incrémental).
|
|
||||||
6. **Approbation finale** puis **squash and merge**, suppression de la branche, carte Kanban déplacée en `Terminé`.
|
|
||||||
7. **Post-merge** : vérification que `main` reste verte (CI sur `main`), et mise à jour de la doc/du `CHANGELOG` si nécessaire.
|
|
||||||
|
|
||||||
### 4.2 Nombre d'approbations
|
|
||||||
|
|
||||||
| Contexte | Approbations requises | Pourquoi |
|
|
||||||
| --- | --- | --- |
|
|
||||||
| Binôme (notre cas) | **1 approbation** par l'autre membre + CI verte | 2 approbations sont impossibles : l'auteur ne peut pas approuver sa propre PR, l'exiger bloquerait tout le monde |
|
|
||||||
| Équipe de 3 à 5 | **2 approbations** | Réduit le risque d'angle mort et partage la connaissance |
|
|
||||||
| Équipe > 5 / code critique | **2 approbations dont un `CODEOWNER`** | Le propriétaire de la zone est garant de sa cohérence |
|
|
||||||
| `hotfix` en urgence | **1 approbation**, rétro-revue sous 48 h | On débloque la production sans perdre la trace |
|
|
||||||
|
|
||||||
**Notre règle** : 1 approbation humaine **plus** les contrôles automatiques obligatoires. Le relecteur ne « remplace » pas la CI et la CI ne remplace pas le relecteur : les deux sont nécessaires. Une PR approuvée dont un nouveau commit casse la CI repasse en revue (l'approbation est invalidée).
|
|
||||||
|
|
||||||
### 4.3 Critères de validation avant fusion (Definition of Done)
|
|
||||||
|
|
||||||
Une PR n'est fusionnable que si **tous** ces points sont vrais :
|
|
||||||
|
|
||||||
- [ ] L'issue est liée (`Fixes #…`) et les critères d'acceptation sont couverts.
|
|
||||||
- [ ] **CI verte** : `lint` (`ruff check`, `gofmt`/`go vet`), `tests` (`go test ./kittens/file_manager/`, `./test.py` pertinents), `build` (`./dev.sh build`).
|
|
||||||
- [ ] **Code relu et approuvé** par l'autre membre ; tous les commentaires sont résolus.
|
|
||||||
- [ ] **Commits clairs** : format Conventional Commits, messages en anglais, pas de `wip` résiduel.
|
|
||||||
- [ ] **Aucun fichier parasite** versionné : pas de `*_generated.go`, `dependencies/`, fichiers d'environnement, secrets, artefacts de build (voir `.gitignore`).
|
|
||||||
- [ ] **Documentation à jour** : `README.md`, `docs/kittens/file-manager.rst`, aide des options si un réglage est ajouté ou renommé.
|
|
||||||
- [ ] **Tests ajoutés** pour toute nouvelle logique (fonctions pures du panneau, cas limites : caractères larges, chemins vides, permissions).
|
|
||||||
- [ ] **Pas de régression** : les cas d'erreur restent gérés (répertoire non vide, fichier non inscriptible).
|
|
||||||
- [ ] **Portée respectée** : la PR ne fait que ce que dit l'issue ; le reste part dans une autre PR.
|
|
||||||
- [ ] **Branche à jour** avec `main` et **pas de conflit**.
|
|
||||||
- [ ] **Performance** : pas de boucle coûteuse ajoutée dans le rendu (un benchmark est joint si la PR touche le chemin chaud).
|
|
||||||
- [ ] **Sécurité** : aucune commande shell construite par concaténation non échappée, aucun secret dans le diff.
|
|
||||||
|
|
||||||
Gabarit de PR (`.github/pull_request_template.md`, résumé) :
|
|
||||||
|
|
||||||
```md
|
|
||||||
## Contexte
|
|
||||||
Fixes #42 — création de fichiers depuis la ligne d'état.
|
|
||||||
|
|
||||||
## Changements
|
|
||||||
- `main.go` : action `create_file`.
|
|
||||||
- `main.py` : raccourci `n` et option `show_hidden` vérifiée.
|
|
||||||
|
|
||||||
## Comment tester
|
|
||||||
1. `./dev.sh build`
|
|
||||||
2. `kitten file-manager ~/tmp`, puis `n`, saisir `test.txt`
|
|
||||||
|
|
||||||
## Checklist
|
|
||||||
- [ ] CI verte - [ ] Tests ajoutés - [ ] Doc mise à jour - [ ] Aucun secret
|
|
||||||
```
|
|
||||||
|
|
||||||
### 4.4 Bonnes pratiques de revue
|
|
||||||
|
|
||||||
- **PR courtes** : viser **≤ 400 lignes modifiées**. Au-delà, le taux de détection de bugs s'effondre ; on découpe.
|
|
||||||
- **Relire le code, pas la personne** : commenter le comportement et proposer une alternative, jamais juger l'auteur.
|
|
||||||
- **Commentaires actionnables** : « Ici, `filepath.Join` évite le cas `//` sur Windows » plutôt que « c'est mauvais ».
|
|
||||||
- **Préfixer le niveau d'exigence** : `[bloquant]`, `[suggestion]`, `[question]`, `[nit]` pour distinguer ce qui empêche la fusion du simple confort.
|
|
||||||
- **Ne pas réécrire la PR de l'autre** : on propose, l'auteur applique (sauf correction triviale de coquille, annoncée en commentaire).
|
|
||||||
- **Le relecteur vérifie en local** quand le changement est subtil (`git fetch origin && git switch <branche>`, puis test manuel) : le diff ne remplace pas l'exécution.
|
|
||||||
- **Pas de « LGTM » sec** : une approbation indique ce qui a été vérifié (code lu, tests lancés, cas limites testés).
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 5. Bonnes pratiques de collaboration (question d)
|
|
||||||
|
|
||||||
### 5.1 Fréquence de commit et de push
|
|
||||||
|
|
||||||
| Action | Fréquence recommandée | Raison |
|
|
||||||
| --- | --- | --- |
|
|
||||||
| **Commit** | À chaque unité de travail cohérente : 3 à 10 par jour, ~50 à 200 lignes | Point de sauvegarde, message lisible, retour arrière ciblé |
|
|
||||||
| **Push** | **Au moins 1 fois par demi-journée**, et toujours en fin de journée | Sauvegarde distante, CI lancée tôt, travail visible du binôme |
|
|
||||||
| **Pull request** | Dès que la fonctionnalité est testable (même incomplète, en brouillon) | Relecture précoce, conflits détectés tôt |
|
|
||||||
| **Synchronisation `main`** | Chaque matin + dès qu'une PR est fusionnée | Branche courte = conflits rares et simples |
|
|
||||||
|
|
||||||
Anti-modèles : garder 3 jours de travail non poussé (perte de données, conflit géant), pousser 20 fois par heure des commits `wip` non relisibles, ouvrir une PR de 2 000 lignes.
|
|
||||||
|
|
||||||
### 5.2 Gestion des conflits de merge
|
|
||||||
|
|
||||||
**Prévention (le plus important)** :
|
|
||||||
|
|
||||||
1. Branches **courtes** et périmètre étroit ; découpage par fichier/zone pour que les deux ne touchent pas les mêmes lignes.
|
|
||||||
2. `git fetch` + `rebase origin/main` **quotidien** sur sa branche personnelle.
|
|
||||||
3. Fichiers sensibles aux conflits (`CHANGELOG.md`, fichiers générés) : on ne les édite pas dans deux branches en parallèle ; le `CHANGELOG` est consolidé dans la PR de release.
|
|
||||||
4. Formateurs et fins de ligne imposés (`.editorconfig`, `.gitattributes`) : pas de faux conflits de whitespace/CRLF.
|
|
||||||
|
|
||||||
**Résolution** :
|
|
||||||
|
|
||||||
```sh
|
|
||||||
git fetch origin
|
|
||||||
git switch feat/file-manager-create-entry
|
|
||||||
git rebase origin/main
|
|
||||||
# conflit : git status liste les fichiers
|
|
||||||
# résoudre à la main, puis :
|
|
||||||
git add <fichier-résolu>
|
|
||||||
git rebase --continue
|
|
||||||
# en cas de doute, repartir de zéro :
|
|
||||||
git rebase --abort
|
|
||||||
```
|
|
||||||
|
|
||||||
- **On ne résout jamais un conflit sans comprendre les deux versions** : `git log --merge -p <fichier>` et l'issue/PR d'origine donnent l'intention de chaque côté.
|
|
||||||
- **Résolution testée** : après un rebase, `./dev.sh build` + tests concernés, puis `git push --force-with-lease` (jamais `--force` nu).
|
|
||||||
- **Escalade** : si le conflit dépasse 15 minutes ou touche du code que l'autre connaît mieux, **on s'appelle**. On ne fusionne pas un conflit à l'aveugle pour « avancer ».
|
|
||||||
- **Sur une branche partagée**, jamais de rebase : on fusionne `main` dans la branche (`git merge origin/main`), sinon tous les relecteurs perdent la trace.
|
|
||||||
- Conflits récurrents = signal d'alerte : on revoit le découpage des tâches, pas seulement le conflit.
|
|
||||||
|
|
||||||
### 5.3 Traçabilité des décisions
|
|
||||||
|
|
||||||
Chaque décision doit pouvoir être retrouvée en remontant la chaîne **issue → branche → commit → PR → tag** :
|
|
||||||
|
|
||||||
- **Issue** : le *quoi* et le *pourquoi* (contexte, critères d'acceptation). Numérotée, étiquetée, assignée.
|
|
||||||
- **Branche** : porte le numéro de l'issue quand c'est naturel (`feat/42-create-entry`).
|
|
||||||
- **Commit** : Conventional Commits, corps expliquant le *pourquoi* d'un choix non évident (compromis, cas limite).
|
|
||||||
- **PR** : description complète, discussion de revue, décisions actées. Une PR référence l'issue (`Fixes #42`), l'issue référence la PR.
|
|
||||||
- **ADRs** : décision structurante → court fichier `docs/adr/003-squash-and-merge.md` (contexte, options, décision, conséquences), commité. Immutable : une nouvelle décision remplace l'ancienne par un nouvel ADR.
|
|
||||||
- **`CHANGELOG.md`** : ce qui change pour l'utilisateur, par version.
|
|
||||||
- **Labels + board** : état du travail visible sans lire tout l'historique.
|
|
||||||
- **Messages de PR/commit sans mention d'outil** : on documente le changement et sa raison, jamais l'assistant ou l'outil utilisé.
|
|
||||||
|
|
||||||
### 5.4 Garantir la qualité avant intégration
|
|
||||||
|
|
||||||
| Niveau | Contrôle | Quand |
|
|
||||||
| --- | --- | --- |
|
|
||||||
| **Local** | hooks `pre-commit` (ruff, gofmt, détection de secrets), `.gitmessage` | Avant chaque commit |
|
|
||||||
| **Branche** | CI GitHub Actions : lint, tests unitaires, build | À chaque push |
|
|
||||||
| **PR** | Mémoire : gabarit rempli, checklist cochée, CI obligatoire | Avant revue |
|
|
||||||
| **Revue** | Relecture humaine, test local si nécessaire, 1 approbation | Avant fusion |
|
|
||||||
| **`main`** | CI sur `main` après fusion, tag SemVer, release notes | À chaque fusion importante |
|
|
||||||
|
|
||||||
Pipeline CI cible (`.github/workflows/ci.yml`, extrait) :
|
|
||||||
|
|
||||||
```yaml
|
|
||||||
name: CI
|
|
||||||
on:
|
|
||||||
pull_request:
|
|
||||||
push:
|
|
||||||
branches: [main]
|
|
||||||
jobs:
|
|
||||||
lint:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
- run: ruff check .
|
|
||||||
- run: gofmt -l . && go vet ./kittens/file_manager/
|
|
||||||
tests:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
- run: go test ./kittens/file_manager/
|
|
||||||
- run: ./test.py type-check
|
|
||||||
build:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
- run: ./dev.sh deps && ./dev.sh build
|
|
||||||
```
|
|
||||||
|
|
||||||
- **`main` reste toujours verte** : c'est la garantie qu'un `pull` ne casse pas le travail de l'autre.
|
|
||||||
- **Règles d'hygiène** : `.gitignore` à la racine, jamais de secrets/`.env`, jamais de `git add .` aveugle, jamais de `git push --force` sur une branche partagée, commits signés.
|
|
||||||
- **Dette technique** : chaque `TODO` ou contournement crée une issue étiquetée `dette` ; on ne le laisse pas dans un commentaire orphelin.
|
|
||||||
|
|
||||||
### 5.5 Rythme de travail et discipline d'équipe
|
|
||||||
|
|
||||||
- **Point quotidien de 15 min** : hier / aujourd'hui / bloqué.
|
|
||||||
- **Revue croisée systématique** : personne ne fusionne sans l'autre.
|
|
||||||
- **Arrêt propre** : en fin de journée, la branche est poussée, la carte Kanban est à jour, l'état est décrit en commentaire si le travail est incomplet.
|
|
||||||
- **Pas de travail « fantôme »** : un gros chantier en local pendant une semaine est interdit ; on découpe, on pousse, on montre.
|
|
||||||
- **Bilan d'itération** : ce qui a marché, ce qui a coincé, un ajustement de la méthodologie (ce document est versionné et évolue).
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 6. Justification du choix : avantages et limites
|
|
||||||
|
|
||||||
### Avantages
|
|
||||||
|
|
||||||
1. **Feedback rapide** : branches de 1 à 3 jours + CI sur chaque push → une erreur est détectée en heures, pas en fin de projet.
|
|
||||||
2. **`main` fiable** : chaque commit de `main` est revu, linté, testé, compilé. On peut livrer ou repartir d'une base saine à tout moment.
|
|
||||||
3. **Conflits limités** : branches courtes, rebase quotidien, découpage par zone ; les rares conflits restent petits et compréhensibles.
|
|
||||||
4. **Traçabilité complète** : issue → branche → commit → PR → tag ; on peut justifier chaque ligne et chaque décision des mois plus tard.
|
|
||||||
5. **Qualité partagée** : la relecture croisée diffuse la connaissance des deux zones du code et évite le bus factor de 1.
|
|
||||||
6. **Coût d'outillage quasi nul** : tout vit dans GitHub (issues, board, PR, CI, releases), rien à installer ni à administrer.
|
|
||||||
7. **Historique lisible** : squash + Conventional Commits + tags SemVer donnent un journal clair, exploitable pour un `CHANGELOG` et des releases automatiques.
|
|
||||||
8. **Transposable** : ces règles s'appliquent telles quelles à une équipe de 5 ou 10 (2 approbations, CODEOWNERS), ce qui correspond à un contexte professionnel.
|
|
||||||
|
|
||||||
### Limites et parades
|
|
||||||
|
|
||||||
| Limite | Parade retenue |
|
|
||||||
| --- | --- |
|
|
||||||
| **Une seule approbation** = un seul regard, angle mort possible | Checklist obligatoire, CI stricte, relecture en local pour les changements subtils, 2 approbations dès qu'une 3ᵉ personne rejoint |
|
|
||||||
| **Pas de branche `develop`** : pas de zone de stabilisation longue | Branches `release/*` créées ponctuellement quand une version doit être gelée |
|
|
||||||
| **Coût de la revue** : avec deux personnes, l'attente de relecture peut bloquer | Objectif de réponse < 24 h, PR courtes, revue en priorité sur le développement ; `Draft PR` pour partager tôt |
|
|
||||||
| **Discipline nécessaire** : GitHub Flow s'effondre si les branches durent des semaines | Règle des 3 jours, découpage des issues, point quotidien, indicateur « âge des branches ouvertes » |
|
|
||||||
| **Squash** : perte de la granularité des commits intermédiaires | Commits soignés quand même (utiles à la revue), et merge commit pour les `release/*` / `hotfix/*` |
|
|
||||||
| **Petit effectif** : rôles cumulés, risque de relâchement sur la doc et la CI | Rôles tournants par itération, checklist non négociable, CI bloquante sur `main` |
|
|
||||||
| **Conventions à apprendre** (Conventional Commits, SemVer) | `.gitmessage` + Commitlint en local, exemples dans ce document, rappel dans `CONTRIBUTING.md` |
|
|
||||||
| **Dépendance à GitHub** | Le dépôt Git reste la source de vérité (utilisable hors ligne) ; le workflow ne repose pas sur une fonctionnalité propriétaire indispensable |
|
|
||||||
|
|
||||||
### Alternatives écartées, en résumé
|
|
||||||
|
|
||||||
- **Git Flow** : surdimensionné pour deux développeurs ; `develop` + `release` + `hotfix` permanents créent de l'attente et des merges massifs.
|
|
||||||
- **Feature Branch sans PR** : rien ne garantit la qualité de `main`, et la revue devient optionnelle.
|
|
||||||
- **Trunk-based avec développement direct sur `main`** : trop risqué ici — le code touche au shell (suppression de fichiers, `cd`), une régression non revue est coûteuse ; viable avec des feature flags et une CI très mature, ce qui n'est pas l'objectif du projet.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 7. Récapitulatif — la méthodologie en dix lignes
|
|
||||||
|
|
||||||
1. Une **seule branche longue** : `main`, protégée, toujours verte.
|
|
||||||
2. Des branches de travail **courtes** nommées `type/description` (≤ 3 jours).
|
|
||||||
3. **Une issue = une branche = une PR**, périmètre strict.
|
|
||||||
4. Workflow **GitHub Flow**, fusion en **squash and merge**.
|
|
||||||
5. **Conventional Commits** en anglais, un commit = un changement cohérent.
|
|
||||||
6. **SemVer** + tags signés `vX.Y.Z` + `CHANGELOG`.
|
|
||||||
7. **PR obligatoire** : gabarit rempli, CI verte, checklist cochée.
|
|
||||||
8. **1 approbation** par le binôme (2 dès une équipe de 3+).
|
|
||||||
9. **Push au moins deux fois par jour**, rebase quotidien, conflits résolus à deux.
|
|
||||||
10. **Toute décision est écrite sur GitHub** : issue, PR ou ADR — sinon elle n'existe pas.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 8. Annexes
|
|
||||||
|
|
||||||
### 8.1 Checklist express avant de demander une revue
|
|
||||||
|
|
||||||
```
|
|
||||||
[ ] Ma branche est à jour avec main et la CI est verte
|
|
||||||
[ ] Mon diff fait moins de ~400 lignes, sinon il est découpé
|
|
||||||
[ ] J'ai lié l'issue et rempli la description (contexte, tests)
|
|
||||||
[ ] J'ai relu mon propre diff (git diff main...HEAD)
|
|
||||||
[ ] Aucun fichier généré, secret ou artefact n'est versionné
|
|
||||||
[ ] La doc et les tests sont à jour
|
|
||||||
```
|
|
||||||
|
|
||||||
### 8.2 Commandes utiles
|
|
||||||
|
|
||||||
```sh
|
|
||||||
git switch -c feat/<sujet> # nouvelle branche
|
|
||||||
git fetch origin && git rebase origin/main
|
|
||||||
git log --oneline --graph --decorate # vue de l'historique
|
|
||||||
git diff main...HEAD # relire tout son travail avant PR
|
|
||||||
git rebase --interactive origin/main # nettoyer ses commits (branche perso)
|
|
||||||
git push --force-with-lease # après rebase, sans risque pour autrui
|
|
||||||
git tag -s v0.51.0 -m "release" # tag signé
|
|
||||||
git shortlog -sn --no-merges # répartition des contributions
|
|
||||||
```
|
|
||||||
@@ -213,10 +213,6 @@ _ksi_main() {
|
|||||||
builtin printf "\e]7;kitty-shell-cwd://%s%s\a" "$HOSTNAME" "$PWD"
|
builtin printf "\e]7;kitty-shell-cwd://%s%s\a" "$HOSTNAME" "$PWD"
|
||||||
fi
|
fi
|
||||||
fi
|
fi
|
||||||
|
|
||||||
if [[ -n "${_ksi_cwd_sync_file:-}" ]]; then
|
|
||||||
_ksi_cwd_sync_apply
|
|
||||||
fi
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if [[ "${_ksi_prompt[cursor]}" == "y" ]]; then
|
if [[ "${_ksi_prompt[cursor]}" == "y" ]]; then
|
||||||
@@ -269,35 +265,9 @@ _ksi_main() {
|
|||||||
_ksi_prompt[ps2]+="\[\e]133;A;k=s\a\]"
|
_ksi_prompt[ps2]+="\[\e]133;A;k=s\a\]"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# Optional working directory sync with the file manager panel (sync_cwd).
|
|
||||||
# The panel publishes the directory it wants in <dir>/<window id>.set and we
|
|
||||||
# apply it at prompt time instead of typing a cd into the terminal: the
|
|
||||||
# command stays out of the history and a half typed multi-line command is
|
|
||||||
# not submitted. We publish our own directory the same way so that the panel
|
|
||||||
# can follow a cd made here.
|
|
||||||
if [[ -n "$KITTY_CWD_SYNC_DIR" && -n "$KITTY_WINDOW_ID" && -d "$KITTY_CWD_SYNC_DIR" ]]; then
|
|
||||||
_ksi_cwd_sync_file="$KITTY_CWD_SYNC_DIR/$KITTY_WINDOW_ID"
|
|
||||||
_ksi_cwd_sync_publish() {
|
|
||||||
builtin printf '%s' "$PWD" > "$_ksi_cwd_sync_file" 2> /dev/null
|
|
||||||
builtin return 0
|
|
||||||
}
|
|
||||||
_ksi_cwd_sync_apply() {
|
|
||||||
builtin local ret=$? target
|
|
||||||
if [[ -f "$_ksi_cwd_sync_file.set" ]]; then
|
|
||||||
IFS= builtin read -r target < "$_ksi_cwd_sync_file.set"
|
|
||||||
builtin command rm -f -- "$_ksi_cwd_sync_file.set"
|
|
||||||
if [[ -n "$target" && -d "$target" ]]; then
|
|
||||||
builtin cd -- "$target"
|
|
||||||
fi
|
|
||||||
fi
|
|
||||||
_ksi_cwd_sync_publish
|
|
||||||
builtin return $ret
|
|
||||||
}
|
|
||||||
_ksi_cwd_sync_publish
|
|
||||||
fi
|
|
||||||
|
|
||||||
builtin alias edit-in-kitty="kitten edit-in-kitty"
|
builtin alias edit-in-kitty="kitten edit-in-kitty"
|
||||||
|
|
||||||
|
|
||||||
if [[ "${_ksi_prompt[complete]}" == "y" ]]; then
|
if [[ "${_ksi_prompt[complete]}" == "y" ]]; then
|
||||||
_ksi_completions() {
|
_ksi_completions() {
|
||||||
builtin local src
|
builtin local src
|
||||||
@@ -345,7 +315,6 @@ _ksi_main() {
|
|||||||
# from the shell
|
# from the shell
|
||||||
builtin local pc
|
builtin local pc
|
||||||
pc='builtin declare -F _ksi_prompt_command > /dev/null 2> /dev/null && _ksi_prompt_command'
|
pc='builtin declare -F _ksi_prompt_command > /dev/null 2> /dev/null && _ksi_prompt_command'
|
||||||
if [[ -n "${_ksi_cwd_sync_file:-}" ]]; then pc="$pc; _ksi_cwd_sync_apply"; fi
|
|
||||||
if [[ -z "${PROMPT_COMMAND[*]}" ]]; then
|
if [[ -z "${PROMPT_COMMAND[*]}" ]]; then
|
||||||
PROMPT_COMMAND=([0]="$pc")
|
PROMPT_COMMAND=([0]="$pc")
|
||||||
elif [[ $(builtin declare -p PROMPT_COMMAND 2> /dev/null) =~ 'declare -a PROMPT_COMMAND' ]]; then
|
elif [[ $(builtin declare -p PROMPT_COMMAND 2> /dev/null) =~ 'declare -a PROMPT_COMMAND' ]]; then
|
||||||
|
|||||||
@@ -137,28 +137,6 @@ function __ksi_schedule --on-event fish_prompt -d "Setup kitty integration after
|
|||||||
__update_cwd_osc
|
__update_cwd_osc
|
||||||
end
|
end
|
||||||
|
|
||||||
# Optional working directory sync with the file manager panel (sync_cwd).
|
|
||||||
# The panel publishes the directory it wants in <dir>/<window id>.set and we
|
|
||||||
# apply it at prompt time instead of typing a cd into the terminal, see the
|
|
||||||
# bash integration for the rationale.
|
|
||||||
if set -q KITTY_CWD_SYNC_DIR; and set -q KITTY_WINDOW_ID; and test -d "$KITTY_CWD_SYNC_DIR"
|
|
||||||
function __ksi_cwd_sync_publish --on-event fish_prompt -d "Publish the working directory for the file manager panel"
|
|
||||||
printf '%s' "$PWD" > "$KITTY_CWD_SYNC_DIR/$KITTY_WINDOW_ID" 2> /dev/null
|
|
||||||
end
|
|
||||||
function __ksi_cwd_sync_apply --on-event fish_prompt -d "Apply a directory chosen in the file manager panel"
|
|
||||||
set --local file "$KITTY_CWD_SYNC_DIR/$KITTY_WINDOW_ID.set"
|
|
||||||
if test -f "$file"
|
|
||||||
set --local target (cat "$file")
|
|
||||||
rm -f -- "$file"
|
|
||||||
if test -n "$target" -a -d "$target"
|
|
||||||
builtin cd -- "$target"
|
|
||||||
end
|
|
||||||
end
|
|
||||||
__ksi_cwd_sync_publish
|
|
||||||
end
|
|
||||||
__ksi_cwd_sync_publish
|
|
||||||
end
|
|
||||||
|
|
||||||
# Note that neither alias nor function is recursive in fish so if the user defines an alias/function
|
# Note that neither alias nor function is recursive in fish so if the user defines an alias/function
|
||||||
# for sudo/run0 it will be clobbered by us, so only install these if they are not already functions
|
# for sudo/run0 it will be clobbered by us, so only install these if they are not already functions
|
||||||
if not contains "no-sudo" $_ksi
|
if not contains "no-sudo" $_ksi
|
||||||
|
|||||||
@@ -246,31 +246,6 @@ _ksi_deferred_init() {
|
|||||||
_ksi_report_pwd
|
_ksi_report_pwd
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# Optional working directory sync with the file manager panel (sync_cwd).
|
|
||||||
# The panel publishes the directory it wants in <dir>/<window id>.set and we
|
|
||||||
# apply it at prompt time instead of typing a cd into the terminal, see the
|
|
||||||
# bash integration for the rationale.
|
|
||||||
if [[ -n $KITTY_CWD_SYNC_DIR && -n $KITTY_WINDOW_ID && -d $KITTY_CWD_SYNC_DIR ]]; then
|
|
||||||
builtin typeset -g _ksi_cwd_sync_file="$KITTY_CWD_SYNC_DIR/$KITTY_WINDOW_ID"
|
|
||||||
_ksi_cwd_sync_publish() { builtin print -rn -- "$PWD" >| "$_ksi_cwd_sync_file" 2> /dev/null; }
|
|
||||||
_ksi_cwd_sync_apply() {
|
|
||||||
builtin local -i ret=$?
|
|
||||||
builtin local target
|
|
||||||
if [[ -f "$_ksi_cwd_sync_file.set" ]]; then
|
|
||||||
IFS= builtin read -r target < "$_ksi_cwd_sync_file.set"
|
|
||||||
builtin command rm -f -- "$_ksi_cwd_sync_file.set"
|
|
||||||
if [[ -n $target && -d $target ]]; then
|
|
||||||
builtin cd -- "$target"
|
|
||||||
fi
|
|
||||||
fi
|
|
||||||
_ksi_cwd_sync_publish
|
|
||||||
builtin return ret
|
|
||||||
}
|
|
||||||
_ksi_cwd_sync_publish
|
|
||||||
precmd_functions+=(_ksi_cwd_sync_apply)
|
|
||||||
chpwd_functions+=(_ksi_cwd_sync_publish)
|
|
||||||
fi
|
|
||||||
|
|
||||||
# Enable terminal title changes.
|
# Enable terminal title changes.
|
||||||
if (( ! opt[(Ie)no-title] )); then
|
if (( ! opt[(Ie)no-title] )); then
|
||||||
# We don't use `print -P` because it depends on prompt options, which
|
# We don't use `print -P` because it depends on prompt options, which
|
||||||
|
|||||||
+1
-2
@@ -30,8 +30,7 @@ func ShowError(err error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (self *Command) version_string(formatter *markup.Context) string {
|
func (self *Command) version_string(formatter *markup.Context) string {
|
||||||
return fmt.Sprintln(formatter.Italic(self.CommandStringForUsage()), formatter.Opt(kitty.VersionString+kitty.VersionSuffix), "created by", formatter.Title("Kovid Goyal")) +
|
return fmt.Sprintln(formatter.Italic(self.CommandStringForUsage()), formatter.Opt(kitty.VersionString+kitty.VersionSuffix), "created by", formatter.Title("Kovid Goyal"))
|
||||||
fmt.Sprintln(formatter.Italic("fws-kitty"), formatter.Opt("0.1.6"), "by", formatter.Title("BlackAngelTV"))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (self *Command) ShowVersion() {
|
func (self *Command) ShowVersion() {
|
||||||
|
|||||||
+5
-21
@@ -97,21 +97,6 @@ func shell_loop(rl *readline.Readline, kill_if_signaled bool) (int, error) {
|
|||||||
return 0, nil
|
return 0, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// launch_shortcuts_panel opens the searchable keybinding reference in a dock,
|
|
||||||
// next to the terminal, instead of taking over the shell window.
|
|
||||||
func launch_shortcuts_panel() int {
|
|
||||||
kitty := utils.KittyExe()
|
|
||||||
if kitty == "" {
|
|
||||||
kitty = "kitty"
|
|
||||||
}
|
|
||||||
root := cli.NewRootCommand()
|
|
||||||
EntryPoint(root)
|
|
||||||
return root.ExecArgs([]string{
|
|
||||||
"kitten", "@", "launch", "--type=window-dock", "--dock-edge=left", "--dock-size=60",
|
|
||||||
kitty, "+kitten", "help",
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func show_basic_help() {
|
func show_basic_help() {
|
||||||
output := strings.Builder{}
|
output := strings.Builder{}
|
||||||
fmt.Fprintln(&output, "Control kitty by sending it commands.")
|
fmt.Fprintln(&output, "Control kitty by sending it commands.")
|
||||||
@@ -125,7 +110,7 @@ func show_basic_help() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
fmt.Fprintln(&output, " ", formatter.Green("help"))
|
fmt.Fprintln(&output, " ", formatter.Green("help"))
|
||||||
fmt.Fprintln(&output, " ", "Show keyboard shortcuts")
|
fmt.Fprintln(&output, " ", "Show this help")
|
||||||
fmt.Fprintln(&output, " ", formatter.Green("exit"))
|
fmt.Fprintln(&output, " ", formatter.Green("exit"))
|
||||||
fmt.Fprintln(&output, " ", "Exit this shell")
|
fmt.Fprintln(&output, " ", "Exit this shell")
|
||||||
cli.ShowHelpInPager(output.String())
|
cli.ShowHelpInPager(output.String())
|
||||||
@@ -151,14 +136,14 @@ func exec_command(at_root_command *cli.Command, rl *readline.Readline, cmdline s
|
|||||||
hi.ExitCode = 0
|
hi.ExitCode = 0
|
||||||
defer rl.AddHistoryItem(hi)
|
defer rl.AddHistoryItem(hi)
|
||||||
if len(parsed_cmdline) == 1 {
|
if len(parsed_cmdline) == 1 {
|
||||||
hi.ExitCode = launch_shortcuts_panel()
|
show_basic_help()
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
switch parsed_cmdline[1] {
|
switch parsed_cmdline[1] {
|
||||||
case "exit":
|
case "exit":
|
||||||
fmt.Println("Exit this shell")
|
fmt.Println("Exit this shell")
|
||||||
case "help":
|
case "help":
|
||||||
fmt.Println("Show keyboard shortcuts")
|
fmt.Println("Show help")
|
||||||
default:
|
default:
|
||||||
sc := at_root_command.FindSubCommand(parsed_cmdline[1])
|
sc := at_root_command.FindSubCommand(parsed_cmdline[1])
|
||||||
if sc == nil {
|
if sc == nil {
|
||||||
@@ -205,7 +190,7 @@ func completions(before_cursor, after_cursor string) (ans *cli.Completions) {
|
|||||||
}
|
}
|
||||||
x.ShortDescription = desc
|
x.ShortDescription = desc
|
||||||
}
|
}
|
||||||
add_sc("help", "Show keyboard shortcuts")
|
add_sc("help", "Show help")
|
||||||
add_sc("exit", "Exit the kitty shell")
|
add_sc("exit", "Exit the kitty shell")
|
||||||
root.Validate()
|
root.Validate()
|
||||||
ans = root.GetCompletions(argv, nil)
|
ans = root.GetCompletions(argv, nil)
|
||||||
@@ -221,8 +206,7 @@ func shell_main(cmd *cli.Command, args []string) (int, error) {
|
|||||||
running_shell = true
|
running_shell = true
|
||||||
formatter = markup.New(true)
|
formatter = markup.New(true)
|
||||||
fmt.Println("Welcome to the kitty shell!")
|
fmt.Println("Welcome to the kitty shell!")
|
||||||
fmt.Println("Use", formatter.Green("Ctrl+Shift+H"), "or", formatter.Green("help"), "for the keyboard shortcuts panel.")
|
fmt.Println("Use", formatter.Green("help"), "for assistance or", formatter.Green("exit"), "to quit.")
|
||||||
fmt.Println("Use", formatter.Green("help <command>"), "for a command's help, or", formatter.Green("exit"), "to quit.")
|
|
||||||
if atwid := os.Getenv("KITTY_SHELL_ACTIVE_WINDOW_ID"); atwid != "" {
|
if atwid := os.Getenv("KITTY_SHELL_ACTIVE_WINDOW_ID"); atwid != "" {
|
||||||
amsg := "Previously active window id: " + atwid
|
amsg := "Previously active window id: " + atwid
|
||||||
os.Unsetenv("KITTY_SHELL_ACTIVE_WINDOW_ID")
|
os.Unsetenv("KITTY_SHELL_ACTIVE_WINDOW_ID")
|
||||||
|
|||||||
Reference in new issue
Block a user