feat(session): restore the last session with --session=last #40
No files matched your search
@@ -172,16 +172,20 @@ map ctrl+shift+e launch --type=overlay kitten file-manager
|
||||
Un fichier validé s'ouvre dans un nouvel onglet, donc en pleine fenêtre même
|
||||
depuis un dock, et le panneau reprend la main à la fermeture de l'éditeur. En
|
||||
revanche, kitty ne rend jamais le résultat d'un `launch --type=window-dock` au
|
||||
shell : valider un répertoire dans un dock ne peut donc pas faire de `cd`.
|
||||
shell : `Ctrl+Entrée` dans un dock ne peut donc pas faire de `cd`.
|
||||
|
||||
### Raccourcis par défaut
|
||||
|
||||
| Touche | Action |
|
||||
| --- | --- |
|
||||
| `Entrée` | Change le répertoire du shell si la sélection est un répertoire, sinon ouvre le fichier dans l'éditeur, dans un nouvel onglet ; le panneau revient à la fermeture de l'éditeur |
|
||||
| `Entrée` | Ouvre la sélection : entre dans le répertoire, ou ouvre le fichier dans l'éditeur dans un nouvel onglet ; le panneau revient à la fermeture de l'éditeur |
|
||||
| `→` / `L` | Entre dans le répertoire sélectionné sans toucher au shell |
|
||||
| `←` / `Retour arrière` / `H` | Remonte au répertoire parent |
|
||||
| `Ctrl+Entrée` / `C` | Déplace le shell vers le répertoire affiché, sans tenir compte de la sélection |
|
||||
| `/` | Filtre la liste par recherche floue ; `Entrée` ouvre la sélection, `Échap` efface la requête |
|
||||
| `:` | Ouvre la palette des actions, filtrable, `Entrée` exécute l'action |
|
||||
| `O` / `T` | Ouvre le fichier sélectionné dans un nouvel onglet / une nouvelle fenêtre |
|
||||
| `A` | Alias de `Maj+N` : crée un répertoire |
|
||||
| `↑` / `K`, `↓` / `J` | Déplace la sélection |
|
||||
| `Page préc.` / `Ctrl+B`, `Page suiv.` / `Ctrl+F` | Déplace la sélection d'une page |
|
||||
| `Début` / `G`, `Fin` / `Maj+G` | Première / dernière entrée |
|
||||
@@ -198,9 +202,10 @@ Un clic gauche sélectionne une entrée. Tous les raccourcis sont redéfinissabl
|
||||
|
||||
### Limites à connaître
|
||||
|
||||
- `Entrée` et `Ctrl+Entrée` agissent sur la fenêtre qui a lancé le panneau. Dans
|
||||
un dock ou un panneau du bureau, le changement de répertoire n'a personne à
|
||||
qui s'appliquer : lancez l'explorateur depuis un shell pour `cd`.
|
||||
- `Entrée` reste dans le panneau et fonctionne partout, dock compris.
|
||||
`Ctrl+Entrée` agit sur la fenêtre qui a lancé le panneau : dans un dock ou un
|
||||
panneau du bureau, le changement de répertoire n'a personne à qui s'appliquer,
|
||||
lancez l'explorateur depuis un shell pour `cd`.
|
||||
- L'éditeur s'ouvre toujours dans un nouvel onglet, plein écran ; fermer
|
||||
l'éditeur referme l'onglet et rend le panneau tel qu'il était.
|
||||
- L'édition passe par kitty : le fichier doit être accessible en lecture et en
|
||||
@@ -217,7 +222,7 @@ Les réglages vivent dans `~/.config/kitty/file-manager.conf` (même syntaxe que
|
||||
# Afficher les fichiers cachés à l'ouverture
|
||||
show_hidden yes
|
||||
|
||||
# name (défaut) ou mtime (plus récent d'abord)
|
||||
# name (défaut), mtime (plus récent d'abord) ou size (plus gros d'abord)
|
||||
sort_by mtime
|
||||
|
||||
# Remplacer un raccourci
|
||||
@@ -305,7 +310,7 @@ automatisation) est détaillée dans `packaging/README.md`.
|
||||
| `Unknown kitten: file-manager` ou l'aide ne le liste pas | Binaire `kitten` obsolète : relancer `./dev.sh build` et utiliser `kitty/launcher/kitten`. |
|
||||
| `+file-manager is not a known kitten` | Le panneau s'appelle `kitten file-manager` (sans `+`). |
|
||||
| `kitten: command not found` | Les binaires sont dans `kitty/launcher/` : chemin complet, `PATH` ou lien symbolique. |
|
||||
| Le panneau se ferme sans changer de répertoire | Lancé dans un dock : `cd` n'a pas de shell cible. Utiliser `Ctrl+Entrée` depuis une fenêtre de shell. |
|
||||
| `Ctrl+Entrée` ferme le panneau sans changer de répertoire | Lancé dans un dock : `cd` n'a pas de shell cible. Lancer l'explorateur depuis une fenêtre de shell. |
|
||||
| `... is not readable and writeable` en ouvrant un fichier | L'édition passe par kitty et demande un accès en lecture et écriture. Ouvrir le fichier avec `sudo -e` depuis le shell. |
|
||||
| Rien ne s'affiche / pas de fenêtre | Pas de serveur graphique : session X11/Wayland, WSLg, ou socket monté dans Docker. |
|
||||
| `X11/extensions/XInput2.h: No such file` | Installer `libxi` (XInput2). |
|
||||
|
||||
+5
-2
@@ -16,9 +16,12 @@ override OPTS=
|
||||
endif
|
||||
|
||||
# You can set these variables from the command line.
|
||||
# Prefer the tool environment kept at the root of the checkout, so that the
|
||||
# documentation builds without installing its extensions system-wide.
|
||||
VENV ?= ../.venv
|
||||
SPHINXOPTS = -n -q -j auto -T $(FAIL_WARN) $(OPTS)
|
||||
SPHINXBUILD = sphinx-build
|
||||
SPHINXAUTOBUILD = sphinx-autobuild
|
||||
SPHINXBUILD ?= $(if $(wildcard $(VENV)/bin/sphinx-build),$(VENV)/bin/sphinx-build,sphinx-build)
|
||||
SPHINXAUTOBUILD ?= $(if $(wildcard $(VENV)/bin/sphinx-autobuild),$(VENV)/bin/sphinx-autobuild,sphinx-autobuild)
|
||||
SPHINXPROJ = kitty
|
||||
SOURCEDIR = .
|
||||
BUILDDIR = _build
|
||||
|
||||
@@ -222,6 +222,13 @@ Detailed list of changes
|
||||
0.50.1 [unreleased]
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
- 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.
|
||||
|
||||
- :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
|
||||
@@ -242,6 +249,17 @@ Detailed list of changes
|
||||
that it stays usable in a dock. It also copies paths and creates, renames and
|
||||
deletes entries after a confirmation
|
||||
|
||||
- The :doc:`file manager <kittens/file-manager>` can now filter its listing
|
||||
with a fuzzy query (:kbd:`/`), list and run its actions from an in-panel
|
||||
palette (:kbd:`:`), and open the selected file in a new tab (:kbd:`O`) or a
|
||||
new OS window (:kbd:`T`). Entries can also be sorted by size with
|
||||
:code:`sort_by size`.
|
||||
|
||||
- The :doc:`file manager <kittens/file-manager>` documentation now covers its
|
||||
shell integration and its limits (no preview, no volume handling, no
|
||||
recursive deletion, no privileged files), and is listed in the kittens
|
||||
overview next to the other built-in kittens.
|
||||
|
||||
- :doc:`choose-files <kittens/choose-files>`: Fix concurrent custom preview
|
||||
commands occasionally receiving the path of a different file.
|
||||
|
||||
|
||||
@@ -11,8 +11,9 @@ Gestionnaire de fichiers
|
||||
Le gestionnaire de fichiers affiche le contenu d'un répertoire dans un panneau
|
||||
latéral, pilotable entièrement au clavier, et change le répertoire courant du
|
||||
shell qui l'a lancé. Il remplace la plupart des :code:`cd` : on descend dans
|
||||
l'arborescence, on valide, le panneau se ferme et le shell se déplace, sans
|
||||
perdre l'environnement, l'historique ni l'état de la session.
|
||||
l'arborescence avec :kbd:`Entrée`, puis :kbd:`Ctrl+Entrée` ferme le panneau et
|
||||
déplace le shell, sans perdre l'environnement, l'historique ni l'état de la
|
||||
session.
|
||||
|
||||
Le raccourci par défaut :kbd:`Ctrl+Shift+E` ouvre le panneau dans un
|
||||
:ref:`dock <docks>` à gauche de la fenêtre courante. On peut aussi le lancer
|
||||
@@ -32,8 +33,9 @@ est passé en argument ou avec ``--start-dir``.
|
||||
|
||||
Le changement de répertoire ne peut viser que la fenêtre depuis laquelle le
|
||||
panneau a été lancé. Lancé dans un dock ou un panneau du bureau, il ne change
|
||||
donc pas le répertoire du shell : utilisez :kbd:`Ctrl+Entrée` dans une
|
||||
fenêtre de shell.
|
||||
donc pas le répertoire du shell : :kbd:`Ctrl+Entrée` ferme le panneau sans
|
||||
déplacer le shell. Lancez le panneau depuis une fenêtre de shell pour changer
|
||||
de répertoire.
|
||||
|
||||
L'ouverture d'un fichier, elle, fonctionne partout : le panneau confie le
|
||||
fichier à kitty, qui lance l'éditeur dans un nouvel onglet. Le fichier
|
||||
@@ -45,11 +47,10 @@ Actions
|
||||
-------
|
||||
|
||||
:kbd:`Entrée`
|
||||
Si la sélection est un répertoire, il devient le répertoire courant du
|
||||
shell et le panneau se ferme. Si c'est un fichier, il est ouvert dans
|
||||
l'éditeur de kitty (:opt:`editor`, :envvar:`VISUAL` ou :envvar:`EDITOR`)
|
||||
dans un nouvel onglet ; le panneau reste ouvert et retrouve sa sélection
|
||||
lorsque l'éditeur se ferme.
|
||||
Si la sélection est un répertoire, le panneau y descend, exactement comme
|
||||
avec :kbd:`→`. Si c'est un fichier, il est ouvert dans l'éditeur de kitty
|
||||
(:opt:`editor`, :envvar:`VISUAL` ou :envvar:`EDITOR`) dans un nouvel onglet ;
|
||||
le panneau reste ouvert et retrouve sa sélection lorsque l'éditeur se ferme.
|
||||
|
||||
Le nouvel onglet est ce qui donne au fichier toute la fenêtre : dans un
|
||||
dock, exécuter l'éditeur dans le panneau le réduirait à la largeur du dock.
|
||||
@@ -64,17 +65,36 @@ Actions
|
||||
remonte au répertoire parent.
|
||||
|
||||
:kbd:`Ctrl+Entrée` ou :kbd:`C`
|
||||
déplace le shell vers le répertoire affiché, sans tenir compte de la
|
||||
sélection.
|
||||
déplace le shell vers la sélection si c'est un répertoire, sinon vers le
|
||||
répertoire affiché, puis ferme le panneau.
|
||||
|
||||
:kbd:`Tab` et :kbd:`Maj+Tab`
|
||||
passent à l'entrée suivante, respectivement précédente, comme :kbd:`↓` et
|
||||
:kbd:`↑`. Pendant la saisie d'un nom, la tabulation est ignorée : elle ne
|
||||
peut pas faire partie d'un nom de fichier.
|
||||
|
||||
:kbd:`/`
|
||||
filtre la liste à mesure de la saisie, avec la même recherche floue que la
|
||||
palette de commandes. :kbd:`Entrée` ouvre la sélection, :kbd:`Échap`
|
||||
efface la requête et rétablit la liste complète. Un nom de répertoire suivi
|
||||
d'un :code:`/` ne filtre que les répertoires ; la requête est oubliée en
|
||||
changeant de répertoire.
|
||||
|
||||
:kbd:`:`
|
||||
ouvre la palette des actions. Elle liste chaque action avec sa description,
|
||||
se filtre comme la recherche, et :kbd:`Entrée` exécute l'action
|
||||
sélectionnée. La liste est la source unique utilisée par ce document :
|
||||
toutes les actions configurables y figurent.
|
||||
|
||||
:kbd:`O` et :kbd:`T`
|
||||
ouvrent le fichier sélectionné dans un nouvel onglet, respectivement une
|
||||
nouvelle fenêtre du système. Sur un répertoire, elles y entrent sans
|
||||
toucher au répertoire du shell.
|
||||
|
||||
:kbd:`N` et :kbd:`Maj+N`
|
||||
créent un fichier, respectivement un répertoire, dans le répertoire
|
||||
affiché. Le nom se saisit dans la ligne d'état.
|
||||
affiché. Le nom se saisit dans la ligne d'état. :kbd:`A` est un alias de
|
||||
:kbd:`Maj+N`, pour les claviers où la combinaison est peu pratique.
|
||||
|
||||
:kbd:`R`
|
||||
renomme l'entrée sélectionnée.
|
||||
@@ -115,11 +135,19 @@ Les actions disponibles sont :code:`quit`, :code:`move_up`, :code:`move_down`,
|
||||
:code:`page_up`, :code:`page_down`, :code:`home`, :code:`end`,
|
||||
:code:`activate`, :code:`enter_dir`, :code:`parent_dir`, :code:`cd_here`,
|
||||
:code:`toggle_hidden`, :code:`create_file`, :code:`create_dir`,
|
||||
:code:`rename`, :code:`delete`, :code:`copy_path` et :code:`refresh`.
|
||||
:code:`rename`, :code:`delete`, :code:`copy_path`, :code:`refresh`,
|
||||
:code:`search`, :code:`palette`, :code:`open_tab` et :code:`open_window`.
|
||||
:code:`search`, :code:`palette`, :code:`open_tab` et :code:`open_window` sont
|
||||
les actions des raccourcis :kbd:`/`, :kbd:`:`, :kbd:`O` et :kbd:`T`.
|
||||
La palette :kbd:`:` liste ces actions avec leur description, ce qui évite de
|
||||
retourner à ce document pour retrouver un nom.
|
||||
|
||||
Deux réglages d'apparence sont aussi disponibles : ``show_hidden`` affiche les
|
||||
entrées cachées à l'ouverture du panneau et ``sort_by`` vaut ``name`` (tri par
|
||||
nom en ignorant la casse) ou ``mtime`` (tri par date de dernière modification).
|
||||
nom en ignorant la casse), ``mtime`` (tri par date de dernière modification) ou
|
||||
``size`` (tri par taille, du plus gros au plus petit).
|
||||
Les deux réglages peuvent être changés pour la session courante avec
|
||||
:code:`-o show_hidden=yes` et :code:`-o sort_by=mtime`, ou :code:`-o sort_by=size`.
|
||||
|
||||
L'éditeur n'est pas choisi par le panneau : le fichier est confié à kitty, qui
|
||||
utilise son option :opt:`editor` de :file:`kitty.conf`. Quand celle-ci vaut
|
||||
@@ -127,6 +155,40 @@ 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
|
||||
: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/cli-kitten-file_manager.rst
|
||||
@@ -18,6 +18,7 @@
|
||||
kittens/choose-files
|
||||
kittens/dnd
|
||||
kittens/panel
|
||||
kittens/file-manager
|
||||
kittens/remote_file
|
||||
kittens/hyperlinked_grep
|
||||
kittens/transfer
|
||||
@@ -116,4 +117,9 @@ et à créer des programmes autonomes utiles. Quelques kittens importants :
|
||||
:doc:`Presse-papiers <kittens/clipboard>`
|
||||
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>`.
|
||||
@@ -34,6 +34,30 @@ you want to work on the project, simply run:
|
||||
|
||||
You can also set the session in :file:`kitty.conf` via :opt:`startup_session`.
|
||||
|
||||
Restoring the last session
|
||||
----------------------------
|
||||
|
||||
kitty saves the state of its tabs, windows, layouts, working directories and
|
||||
titles when it exits, in :file:`$XDG_STATE_HOME/kitty/last-session.json`
|
||||
(usually :file:`~/.local/state/kitty/last-session.json`). The saved state is
|
||||
limited to 1 MiB and is overwritten at every exit, so it never accumulates.
|
||||
|
||||
To restore it, start kitty with:
|
||||
|
||||
.. code-block:: sh
|
||||
|
||||
kitty --session=last
|
||||
|
||||
The same saved state can be restored inside a running kitty with the
|
||||
:ac:`restore_last_session` action, which is mapped to :kbd:`kitty_mod+alt+r`
|
||||
by default and adds the saved tabs to the current window.
|
||||
|
||||
Restoring is never automatic: without this option the saved state is ignored,
|
||||
so an unexpected state is never imposed on you. A state file that is corrupt,
|
||||
unreadable or too large is discarded and kitty starts normally. :code:`cd`
|
||||
directives whose directory no longer exists are dropped when restoring. Use
|
||||
:ac:`save_as_session` for sessions that must survive beyond the next exit.
|
||||
|
||||
Thus, it is very easy to create sessions and work on projects. To learn how to
|
||||
create more complex sessions, see :ref:`complex_sessions`.
|
||||
|
||||
|
||||
+423
-63
@@ -14,6 +14,7 @@ import (
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/cli"
|
||||
"github.com/kovidgoyal/kitty/tools/config"
|
||||
"github.com/kovidgoyal/kitty/tools/fzf"
|
||||
"github.com/kovidgoyal/kitty/tools/tui"
|
||||
"github.com/kovidgoyal/kitty/tools/tui/loop"
|
||||
"github.com/kovidgoyal/kitty/tools/wcswidth"
|
||||
@@ -27,6 +28,7 @@ type Entry struct {
|
||||
Name string
|
||||
IsDir bool
|
||||
ModTime int64
|
||||
Size int64
|
||||
}
|
||||
|
||||
type input_purpose int
|
||||
@@ -36,6 +38,7 @@ const (
|
||||
input_create_file
|
||||
input_create_dir
|
||||
input_rename
|
||||
input_search
|
||||
)
|
||||
|
||||
// Pure helpers, kept free of terminal state so that they can be unit tested
|
||||
@@ -51,8 +54,15 @@ func sort_entries(entries []Entry, sort_by string) {
|
||||
if a.IsDir != b.IsDir {
|
||||
return a.IsDir
|
||||
}
|
||||
if sort_by == "mtime" && a.ModTime != b.ModTime {
|
||||
return a.ModTime > b.ModTime
|
||||
switch sort_by {
|
||||
case "mtime":
|
||||
if 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)
|
||||
})
|
||||
@@ -72,6 +82,7 @@ func read_dir(dir string, show_hidden bool, sort_by string) ([]Entry, error) {
|
||||
e := Entry{Name: name, IsDir: item.IsDir()}
|
||||
if info, ierr := item.Info(); ierr == nil {
|
||||
e.ModTime = info.ModTime().Unix()
|
||||
e.Size = info.Size()
|
||||
}
|
||||
entries = append(entries, e)
|
||||
}
|
||||
@@ -191,14 +202,20 @@ type Handler struct {
|
||||
screen_size loop.ScreenSize
|
||||
conf *Config
|
||||
cwd string
|
||||
all_entries []Entry
|
||||
entries []Entry
|
||||
selected int
|
||||
scroll int
|
||||
show_hidden bool
|
||||
search_query string
|
||||
input_purpose input_purpose
|
||||
text_buffer string
|
||||
rename_source string
|
||||
confirm_name string
|
||||
palette_open bool
|
||||
palette_query string
|
||||
palette []action_info
|
||||
palette_selected int
|
||||
message string
|
||||
result_action string
|
||||
result_path string
|
||||
@@ -232,9 +249,15 @@ func (h *Handler) load(dir string) error {
|
||||
return err
|
||||
}
|
||||
h.cwd = dir
|
||||
h.all_entries = entries
|
||||
h.entries = entries
|
||||
if h.selected >= len(entries) {
|
||||
h.selected = max(0, len(entries)-1)
|
||||
if h.search_query != "" {
|
||||
if err = h.apply_search(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if h.selected >= len(h.entries) {
|
||||
h.selected = max(0, len(h.entries)-1)
|
||||
}
|
||||
if h.scroll > h.selected {
|
||||
h.scroll = h.selected
|
||||
@@ -277,6 +300,8 @@ func (h *Handler) reload() {
|
||||
}
|
||||
|
||||
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 {
|
||||
h.message = err.Error()
|
||||
h.draw_screen()
|
||||
@@ -395,31 +420,43 @@ func (h *Handler) copy_selected_path() {
|
||||
h.draw_screen()
|
||||
}
|
||||
|
||||
// activate implements the primary action: the selected directory becomes the
|
||||
// working directory of the shell, the selected file is opened in the editor.
|
||||
// activate implements the primary action: the selected directory is opened in
|
||||
// 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.
|
||||
func (h *Handler) activate() {
|
||||
if h.input_purpose == input_search {
|
||||
h.stop_search()
|
||||
}
|
||||
e, ok := h.selected_entry()
|
||||
if !ok {
|
||||
h.lp.Beep()
|
||||
return
|
||||
}
|
||||
path := entry_path(h.cwd, e.Name)
|
||||
if e.IsDir {
|
||||
h.change_shell_dir_to(path)
|
||||
h.enter_dir()
|
||||
return
|
||||
}
|
||||
h.open_file(path)
|
||||
h.open_file(entry_path(h.cwd, e.Name))
|
||||
}
|
||||
|
||||
// edit_args_in is the client side of kitty's edit protocol. The terminal opens
|
||||
// the editor in a new tab or OS window, which gives the file a whole window even
|
||||
// when the panel is docked. The window closes when the editor exits and the
|
||||
// panel is redrawn in place, instead of handing the command to the shell and
|
||||
// disappearing.
|
||||
func edit_args_in(path, window_type string) []string {
|
||||
return []string{"edit-in-kitty", "--type=" + window_type, path}
|
||||
}
|
||||
|
||||
// edit_args is the client side of kitty's edit protocol. The terminal opens the
|
||||
// editor in a new tab, which gives the file a whole window even when the panel
|
||||
// is docked. The tab closes when the editor exits and the panel is redrawn in
|
||||
// place, instead of handing the command to the shell and disappearing.
|
||||
func edit_args(path string) []string {
|
||||
return []string{"edit-in-kitty", "--type=tab", path}
|
||||
return edit_args_in(path, "tab")
|
||||
}
|
||||
|
||||
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()
|
||||
if err != nil {
|
||||
h.message = err.Error()
|
||||
@@ -429,7 +466,7 @@ func (h *Handler) open_file(path string) {
|
||||
// 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.
|
||||
err = h.lp.SuspendAndRun(func() error {
|
||||
cmd := exec.Command(exe, edit_args(path)...)
|
||||
cmd := exec.Command(exe, edit_args_in(path, window_type)...)
|
||||
cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr
|
||||
return cmd.Run()
|
||||
})
|
||||
@@ -473,53 +510,346 @@ func (h *Handler) change_shell_dir() {
|
||||
h.change_shell_dir_to(path)
|
||||
}
|
||||
|
||||
func (h *Handler) perform_action(name string) {
|
||||
switch name {
|
||||
case "quit":
|
||||
h.lp.Quit(0)
|
||||
case "move_up":
|
||||
h.move_selection(-1)
|
||||
case "move_down":
|
||||
h.move_selection(1)
|
||||
case "page_up":
|
||||
type action_info struct {
|
||||
Name string
|
||||
Description string
|
||||
}
|
||||
|
||||
// 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.lp.Quit(0) },
|
||||
"move_up": func(h *Handler) { h.move_selection(-1) },
|
||||
"move_down": func(h *Handler) { h.move_selection(1) },
|
||||
"page_up": func(h *Handler) {
|
||||
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))
|
||||
case "home":
|
||||
},
|
||||
"home": func(h *Handler) {
|
||||
h.selected = 0
|
||||
h.draw_screen()
|
||||
case "end":
|
||||
},
|
||||
"end": func(h *Handler) {
|
||||
if len(h.entries) > 0 {
|
||||
h.selected = len(h.entries) - 1
|
||||
}
|
||||
h.draw_screen()
|
||||
case "parent_dir":
|
||||
h.change_dir(parent_of(h.cwd))
|
||||
case "activate":
|
||||
},
|
||||
"parent_dir": func(h *Handler) { h.change_dir(parent_of(h.cwd)) },
|
||||
"activate": func(h *Handler) { h.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()
|
||||
case "enter_dir":
|
||||
case ev.MatchesPressOrRepeat("up"):
|
||||
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()
|
||||
case "cd_here":
|
||||
h.change_shell_dir()
|
||||
case "toggle_hidden":
|
||||
h.show_hidden = !h.show_hidden
|
||||
h.reload()
|
||||
case "create_file":
|
||||
h.start_input(input_create_file)
|
||||
case "create_dir":
|
||||
h.start_input(input_create_dir)
|
||||
case "rename":
|
||||
h.start_rename()
|
||||
case "delete":
|
||||
h.start_delete()
|
||||
case "copy_path":
|
||||
h.copy_selected_path()
|
||||
case "refresh":
|
||||
h.reload()
|
||||
return
|
||||
}
|
||||
h.open_file_in(entry_path(h.cwd, e.Name), window_type)
|
||||
}
|
||||
|
||||
func (h *Handler) draw_palette_list(width, list_start, list_height int) {
|
||||
if len(h.palette) == 0 {
|
||||
return
|
||||
}
|
||||
offset := 0
|
||||
if h.palette_selected >= list_height {
|
||||
offset = h.palette_selected - list_height + 1
|
||||
}
|
||||
for row := 0; row < list_height; row++ {
|
||||
idx := offset + row
|
||||
if idx >= len(h.palette) {
|
||||
break
|
||||
}
|
||||
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 {
|
||||
if h.input_purpose == input_search {
|
||||
return h.handle_search_key(ev)
|
||||
}
|
||||
switch {
|
||||
case ev.MatchesPressOrRepeat("escape"):
|
||||
ev.Handled = true
|
||||
@@ -558,6 +888,9 @@ func (h *Handler) on_key_event(ev *loop.KeyEvent) error {
|
||||
if h.input_purpose != input_none {
|
||||
return h.handle_input_key(ev)
|
||||
}
|
||||
if h.palette_open {
|
||||
return h.handle_palette_key(ev)
|
||||
}
|
||||
if h.confirm_name != "" {
|
||||
return h.handle_confirm_key(ev)
|
||||
}
|
||||
@@ -611,8 +944,20 @@ func (h *Handler) on_text(text string, from_key_event bool, in_bracketed_paste b
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if h.palette_open {
|
||||
h.palette_query += text
|
||||
h.update_palette()
|
||||
h.draw_screen()
|
||||
return nil
|
||||
}
|
||||
if h.input_purpose != input_none {
|
||||
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()
|
||||
}
|
||||
return nil
|
||||
@@ -680,6 +1025,8 @@ func (h *Handler) input_prompt() string {
|
||||
return "New directory:"
|
||||
case input_rename:
|
||||
return fmt.Sprintf("Rename %s to:", h.rename_source)
|
||||
case input_search:
|
||||
return "Search:"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -688,6 +1035,9 @@ func (h *Handler) status_text() string {
|
||||
if h.message != "" {
|
||||
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 {
|
||||
return " Empty directory"
|
||||
}
|
||||
@@ -736,20 +1086,24 @@ func (h *Handler) draw_screen() {
|
||||
}
|
||||
h.scroll = max(0, min(h.scroll, max(0, len(h.entries)-list_height)))
|
||||
|
||||
for row := 0; row < list_height; row++ {
|
||||
idx := h.scroll + row
|
||||
if idx >= len(h.entries) {
|
||||
break
|
||||
}
|
||||
e := h.entries[idx]
|
||||
h.lp.MoveCursorTo(1, list_start+row)
|
||||
switch {
|
||||
case idx == h.selected:
|
||||
h.lp.QueueWriteString(h.lp.SprintStyled("reverse", h.padded_entry_text(e, width)))
|
||||
case e.IsDir:
|
||||
h.lp.QueueWriteString(h.lp.SprintStyled("fg=bright-blue", h.entry_text(e, width)))
|
||||
default:
|
||||
h.lp.QueueWriteString(h.entry_text(e, width))
|
||||
if h.palette_open {
|
||||
h.draw_palette_list(width, list_start, list_height)
|
||||
} else {
|
||||
for row := 0; row < list_height; row++ {
|
||||
idx := h.scroll + row
|
||||
if idx >= len(h.entries) {
|
||||
break
|
||||
}
|
||||
e := h.entries[idx]
|
||||
h.lp.MoveCursorTo(1, list_start+row)
|
||||
switch {
|
||||
case idx == h.selected:
|
||||
h.lp.QueueWriteString(h.lp.SprintStyled("reverse", h.padded_entry_text(e, width)))
|
||||
case e.IsDir:
|
||||
h.lp.QueueWriteString(h.lp.SprintStyled("fg=bright-blue", h.entry_text(e, width)))
|
||||
default:
|
||||
h.lp.QueueWriteString(h.entry_text(e, width))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -758,6 +1112,12 @@ func (h *Handler) draw_screen() {
|
||||
|
||||
h.lp.MoveCursorTo(1, height)
|
||||
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:
|
||||
prompt := h.input_prompt() + " "
|
||||
h.lp.QueueWriteString(h.lp.SprintStyled("fg=bright-yellow", prompt))
|
||||
@@ -769,7 +1129,7 @@ func (h *Handler) draw_screen() {
|
||||
h.lp.QueueWriteString(h.lp.SprintStyled("bold fg=bright-red", fmt.Sprintf("Delete %s? [y/N] ", h.confirm_name)))
|
||||
default:
|
||||
h.lp.SetCursorVisible(false)
|
||||
hints := "Enter: cd/open ->: enter <-: up .: hidden n: new file r: rename d: delete y: copy q: quit"
|
||||
hints := "Enter: open /: search :: actions ->: 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)))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -41,7 +41,8 @@ opt(
|
||||
long_text="""
|
||||
How to order entries. :code:`name` lists directories first, then files, both
|
||||
sorted by name ignoring case. :code:`mtime` lists directories first, then files
|
||||
sorted by last modification time, most recent first.
|
||||
sorted by last modification time, most recent first. :code:`size` lists
|
||||
directories first, then files sorted by size, largest first.
|
||||
""",
|
||||
)
|
||||
|
||||
@@ -92,14 +93,15 @@ map('Select first entry', 'home --allow-fallback=shifted,ascii g home')
|
||||
map('Select last entry', 'end end end')
|
||||
map('Select last entry', 'end shift+g end')
|
||||
map(
|
||||
'Change shell directory or open selection',
|
||||
'Open the selection',
|
||||
'activate enter activate',
|
||||
long_text="""
|
||||
When the selection is a directory it becomes the working directory of the shell
|
||||
that launched the panel. When it is a file, the panel opens it in kitty's editor
|
||||
(:opt:`editor`, :envvar:`VISUAL` or :envvar:`EDITOR`) in a new tab, and is
|
||||
drawn again with the same selection once the editor exits. The new tab is what
|
||||
gives the file a whole window even when the panel runs in a dock.
|
||||
When the selection is a directory it is opened in the panel, exactly like the
|
||||
:ref:`enter_dir <file-manager-shortcuts>` shortcut. When it is a file, the panel
|
||||
opens it in kitty's editor (:opt:`editor`, :envvar:`VISUAL` or
|
||||
:envvar:`EDITOR`) in a new tab, and is drawn again with the same selection once
|
||||
the editor exits. The new tab is what gives the file a whole window even when
|
||||
the panel runs in a dock.
|
||||
""",
|
||||
)
|
||||
map(
|
||||
@@ -107,7 +109,7 @@ map(
|
||||
'enter_dir right enter_dir',
|
||||
long_text="""
|
||||
Move the panel into the selected directory without changing the shell's working
|
||||
directory. Use the :ref:`activate <file-manager-shortcuts>` shortcut to also
|
||||
directory. Use the :ref:`cd_here <file-manager-shortcuts>` shortcut to also
|
||||
change the shell's directory.
|
||||
""",
|
||||
)
|
||||
@@ -127,6 +129,7 @@ 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('Create a new file', 'create_file --allow-fallback=shifted,ascii n create_file')
|
||||
map('Create a new directory', 'create_dir shift+n create_dir')
|
||||
map('Create a new directory', 'create_dir --allow-fallback=shifted,ascii a create_dir')
|
||||
map('Rename the selected entry', 'rename --allow-fallback=shifted,ascii r rename')
|
||||
map(
|
||||
'Delete the selected entry',
|
||||
@@ -138,6 +141,26 @@ confirmation. Directories are never deleted recursively.
|
||||
)
|
||||
map('Copy the path of the selection to the clipboard', 'copy_path --allow-fallback=shifted,ascii y copy_path')
|
||||
map('Reload the current directory', 'refresh --allow-fallback=shifted,ascii ctrl+r refresh')
|
||||
map(
|
||||
'Filter the listing with a fuzzy query',
|
||||
'search --allow-fallback=shifted,ascii / search',
|
||||
long_text="""
|
||||
Filters the listing as text is typed, using the same fuzzy matcher as the
|
||||
command palette. :kbd:`Entrée` opens the selection, :kbd:`Échap` clears the
|
||||
query and restores the full listing.
|
||||
""",
|
||||
)
|
||||
map(
|
||||
'List and run the actions of the panel',
|
||||
'palette --allow-fallback=shifted,ascii : palette',
|
||||
long_text="""
|
||||
Lists every action of the panel with its description, filtered by a fuzzy query,
|
||||
and runs the selected one with :kbd:`Entrée`. The same actions can be bound to
|
||||
dedicated shortcuts in :file:`file-manager.conf`.
|
||||
""",
|
||||
)
|
||||
map('Open the selected file in a new tab', 'open_tab --allow-fallback=shifted,ascii o open_tab')
|
||||
map('Open the selected file in a new OS window', 'open_window --allow-fallback=shifted,ascii t open_window')
|
||||
|
||||
egr()
|
||||
|
||||
|
||||
@@ -3,9 +3,11 @@
|
||||
package file_manager
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestSortEntriesDirectoriesFirstThenByName(t *testing.T) {
|
||||
@@ -213,6 +215,132 @@ 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) {
|
||||
if got := truncate_to_width("abcdef", 3); got != "ab\u2026" {
|
||||
t.Fatalf("unexpected truncation %q", got)
|
||||
|
||||
@@ -2528,6 +2528,7 @@ class Boss:
|
||||
if not self._call_on_quit_watchers({'confirmed': True}):
|
||||
set_application_quit_request(NO_CLOSE_REQUESTED)
|
||||
return
|
||||
self.save_last_session()
|
||||
self.save_session_if_logging_out()
|
||||
set_application_quit_request(IMPERATIVE_CLOSE_REQUESTED)
|
||||
return
|
||||
@@ -2557,9 +2558,20 @@ class Boss:
|
||||
if not self._call_on_quit_watchers({'confirmed': True}):
|
||||
set_application_quit_request(NO_CLOSE_REQUESTED)
|
||||
return
|
||||
self.save_last_session()
|
||||
self.save_session_if_logging_out()
|
||||
set_application_quit_request(IMPERATIVE_CLOSE_REQUESTED if confirmed else NO_CLOSE_REQUESTED)
|
||||
|
||||
def save_last_session(self) -> None:
|
||||
# Must run before the quit request is set: the C side then closes the windows and there is
|
||||
# nothing left to serialize. Saving an empty session is a no-op, so this never clobbers a
|
||||
# good state with a torn down one.
|
||||
from .main import is_panel_kitten
|
||||
from .session_restore import save_session_of
|
||||
|
||||
if not is_panel_kitten():
|
||||
save_session_of(self)
|
||||
|
||||
def save_session_if_logging_out(self) -> None:
|
||||
from .logout_session import is_logout_in_progress
|
||||
|
||||
@@ -3947,6 +3959,13 @@ class Boss:
|
||||
def goto_session(self, *cmdline: str) -> None:
|
||||
goto_session(self, cmdline)
|
||||
|
||||
@ac('session', 'Restore the tabs and windows of the session saved when kitty last quit. See :ref:`sessions`.')
|
||||
def restore_last_session(self) -> None:
|
||||
from .session_restore import restore_last_session_into
|
||||
|
||||
if not restore_last_session_into(self):
|
||||
self.ring_bell_if_allowed()
|
||||
|
||||
@ac('session', 'Save the current kitty state as a session file. See :ref:`save_as_session`.')
|
||||
def save_as_session(self, *cmdline: str) -> None:
|
||||
save_as_session(self, cmdline)
|
||||
|
||||
@@ -86,7 +86,7 @@ def generate_class(defn: Definition, loc: str) -> tuple[str, str]:
|
||||
if isinstance(option, MultiOption):
|
||||
mval: dict[str, dict[str, Any]] = {'macos': {}, 'linux': {}, '': {}}
|
||||
func, typ = option_type_data(option)
|
||||
assert isinstance(func, types.FunctionType)
|
||||
assert callable(func), getattr(func, '__name__', func)
|
||||
for val in option:
|
||||
if val.add_to_default:
|
||||
gr = mval[val.only]
|
||||
@@ -115,7 +115,7 @@ def generate_class(defn: Definition, loc: str) -> tuple[str, str]:
|
||||
func = str
|
||||
elif defn.has_color_table and option.is_color_table_color:
|
||||
func, typ = option_type_data(option)
|
||||
assert isinstance(func, types.FunctionType)
|
||||
assert callable(func), getattr(func, '__name__', func)
|
||||
t(f' ans[{option.name!r}] = {func.__name__}(val)')
|
||||
tc_imports.add((func.__module__, func.__name__))
|
||||
cnum = int(option.name[5:])
|
||||
@@ -130,7 +130,7 @@ def generate_class(defn: Definition, loc: str) -> tuple[str, str]:
|
||||
params = dict(inspect.signature(func).parameters)
|
||||
except Exception:
|
||||
params = {}
|
||||
assert isinstance(func, types.FunctionType)
|
||||
assert callable(func), getattr(func, '__name__', func)
|
||||
if 'dict_with_parse_results' in params:
|
||||
t(f' {func.__name__}(val, ans)')
|
||||
else:
|
||||
@@ -188,7 +188,7 @@ def generate_class(defn: Definition, loc: str) -> tuple[str, str]:
|
||||
for aname, action in defn.actions.items():
|
||||
option_names.add(aname)
|
||||
action_parsers[aname] = func = action.parser_func
|
||||
assert isinstance(func, types.FunctionType)
|
||||
assert callable(func), getattr(func, '__name__', func)
|
||||
th = get_type_hints(func)
|
||||
rettype = th['return']
|
||||
typ = option_type_as_str(rettype)
|
||||
|
||||
@@ -68,6 +68,7 @@ from .options.types import Options
|
||||
from .options.utils import DELETE_ENV_VAR
|
||||
from .os_window_size import edge_spacing, initial_window_size_func
|
||||
from .session import create_sessions, get_os_window_sizing_data
|
||||
from .session_restore import save_session_of
|
||||
from .shaders.slang import load_shader_programs
|
||||
from .types import LayerShellConfig
|
||||
from .utils import (
|
||||
@@ -394,6 +395,8 @@ def _run_app(opts: Options, args: CLIOptions, bad_lines: Sequence[BadLine] = (),
|
||||
try:
|
||||
boss.child_monitor.main_loop()
|
||||
finally:
|
||||
if not _is_panel_kitten:
|
||||
save_session_of(boss)
|
||||
boss.destroy()
|
||||
|
||||
|
||||
|
||||
+41
-11
@@ -2318,18 +2318,18 @@ The alignment of the tab bar, can be one of: :code:`start`, :code:`center`,
|
||||
|
||||
opt(
|
||||
'tab_bar_show_new_tab_button',
|
||||
'no',
|
||||
'yes',
|
||||
option_type='to_bool',
|
||||
long_text="""
|
||||
When set to :code:`yes`, a :code:`+` button is always shown at the end of the
|
||||
tab bar as a clickable shortcut to open a new tab. When set to :code:`no`
|
||||
(the default), the button is hidden at rest but still appears temporarily
|
||||
while a window is being dragged, so it can be used as a drop target to open
|
||||
the window in a new tab.
|
||||
When set to :code:`yes` (the default), a :code:`+` button is always shown at
|
||||
the end of the tab bar as a clickable shortcut to open a new tab. When set to
|
||||
:code:`no`, the button is hidden at rest but still appears temporarily while a
|
||||
window is being dragged, so it can be used as a drop target to open the window
|
||||
in a new tab.
|
||||
""",
|
||||
)
|
||||
|
||||
opt('tab_bar_min_tabs', '2', option_type='tab_bar_min_tabs', long_text='The minimum number of tabs that must exist before the tab bar is shown.')
|
||||
opt('tab_bar_min_tabs', '1', option_type='tab_bar_min_tabs', long_text='The minimum number of tabs that must exist before the tab bar is shown.')
|
||||
|
||||
opt(
|
||||
'tab_switch_strategy',
|
||||
@@ -2450,7 +2450,7 @@ lines is wrapped independently.
|
||||
|
||||
opt(
|
||||
'tab_title_template',
|
||||
'"{fmt.fg.red}{bell_symbol}{activity_symbol}{secure_input_symbol}{fmt.fg.tab}{tab.last_focused_progress_percent}{title}"',
|
||||
'"{fmt.fg.red}{bell_symbol}{activity_symbol}{exit_status_symbol}{secure_input_symbol}{fmt.fg.tab}{tab.last_focused_progress_percent}{title}"',
|
||||
option_type='tab_title_template',
|
||||
long_text="""
|
||||
A template to render the tab title. The default just renders the title with
|
||||
@@ -2473,12 +2473,25 @@ use :code:`{sup.index}`. All data available is:
|
||||
The number of windows in the tab.
|
||||
:code:`num_window_groups`
|
||||
The number of window groups (a window group is a window and all of its overlay windows) in the tab.
|
||||
:code:`last_exit_code`
|
||||
The exit status of the last command that finished in the active window of
|
||||
the tab, or the empty string if it succeeded or no command has finished.
|
||||
Requires :ref:`shell integration <shell_integration>`.
|
||||
:code:`exit_status_symbol`
|
||||
A cross followed by :code:`last_exit_code` when the last command failed,
|
||||
empty otherwise. Requires :ref:`shell integration <shell_integration>`.
|
||||
:code:`secure_input_symbol`
|
||||
A key symbol when secure input is enabled on macOS and the tab is the active tab, empty otherwise.
|
||||
:code:`tab.active_wd`
|
||||
The working directory of the currently active window in the tab
|
||||
(expensive, requires syscall). Use :code:`tab.active_oldest_wd` to get
|
||||
the directory of the oldest foreground process rather than the newest.
|
||||
:code:`tab.active_wd_abbreviated`
|
||||
A compact form of :code:`tab.active_wd` suited to a tab title: the home
|
||||
directory is shown as ``~``, intermediate directories are reduced to
|
||||
their first letter and, when the result is still too long, middle
|
||||
directories are replaced by an ellipsis. For example
|
||||
``~/p/fws-kitty``. Has the same cost as :code:`tab.active_wd`.
|
||||
:code:`tab.active_exe`
|
||||
The name of the executable running in the foreground of the currently
|
||||
active window in the tab (expensive, requires syscall). Use
|
||||
@@ -2518,9 +2531,9 @@ use styling directives, for example:
|
||||
Similarly, for bold and italic:
|
||||
``{fmt.bold}bold{fmt.nobold}normal{fmt.italic}italic{fmt.noitalic}``.
|
||||
The 256 eight terminal colors can be used as ``fmt.fg.color0`` through ``fmt.fg.color255``.
|
||||
Note that for backward compatibility, if :code:`{bell_symbol}` or
|
||||
:code:`{activity_symbol}` are not present in the template, they are prepended to
|
||||
it.
|
||||
Note that for backward compatibility, if :code:`{bell_symbol}`,
|
||||
:code:`{activity_symbol}` or :code:`{exit_status_symbol}` are not present in
|
||||
the template, they are prepended to it.
|
||||
""",
|
||||
)
|
||||
|
||||
@@ -4636,6 +4649,23 @@ shortcuts. For a full description see :doc:`hints kitten </kittens/hints>`.
|
||||
""") # }}}
|
||||
|
||||
|
||||
# shortcuts.session {{{
|
||||
agr('shortcuts.session', 'Sessions')
|
||||
|
||||
map(
|
||||
'Restore the last session',
|
||||
'restore_last_session --allow-fallback=shifted,ascii kitty_mod+alt+r restore_last_session',
|
||||
long_text="""
|
||||
Restores the tabs, windows, layouts and working directories of the session that
|
||||
was saved when kitty last quit, without restarting kitty. The state is written
|
||||
by :code:`quit`; see :ref:`sessions`. If there is nothing to restore, a bell is
|
||||
rung instead.
|
||||
""",
|
||||
)
|
||||
|
||||
egr() # }}}
|
||||
|
||||
|
||||
# shortcuts.misc {{{
|
||||
agr('shortcuts.misc', 'Miscellaneous')
|
||||
|
||||
|
||||
Generated
+1
@@ -4,6 +4,7 @@
|
||||
#include "to-c.h"
|
||||
|
||||
|
||||
|
||||
static void
|
||||
convert_from_python_font_size(PyObject *val, Options *opts) {
|
||||
opts->font_size = PyFloat_AsDouble(val);
|
||||
|
||||
Generated
+6
-4
@@ -695,8 +695,8 @@ class Options:
|
||||
tab_bar_margin_color: kitty.fast_data_types.Color | None = None
|
||||
tab_bar_margin_height: TabBarMarginHeight = TabBarMarginHeight(outer=0, inner=0)
|
||||
tab_bar_margin_width: float = 0
|
||||
tab_bar_min_tabs: int = 2
|
||||
tab_bar_show_new_tab_button: bool = False
|
||||
tab_bar_min_tabs: int = 1
|
||||
tab_bar_show_new_tab_button: bool = True
|
||||
tab_bar_style: choices_for_tab_bar_style = 'fade'
|
||||
tab_fade: tuple[float, ...] = (0.25, 0.5, 0.75, 1.0)
|
||||
tab_powerline_style: choices_for_tab_powerline_style = 'angled'
|
||||
@@ -704,7 +704,7 @@ class Options:
|
||||
tab_switch_strategy: choices_for_tab_switch_strategy = 'previous'
|
||||
tab_title_max_length: int = 0
|
||||
tab_title_max_lines: int = 1
|
||||
tab_title_template: str = '{fmt.fg.red}{bell_symbol}{activity_symbol}{secure_input_symbol}{fmt.fg.tab}{tab.last_focused_progress_percent}{title}'
|
||||
tab_title_template: str = '{fmt.fg.red}{bell_symbol}{activity_symbol}{exit_status_symbol}{secure_input_symbol}{fmt.fg.tab}{tab.last_focused_progress_percent}{title}'
|
||||
tab_title_wrap: int = 0
|
||||
term: str = 'xterm-kitty'
|
||||
terminfo_type: choices_for_terminfo_type = 'path'
|
||||
@@ -1024,12 +1024,14 @@ defaults.map = [
|
||||
KeyDefinition(is_sequence=True, trigger=SingleKey(mods=256, key=112), rest=(SingleKey(key=110),), options=KeyMapOptions(when_focus_on='', new_mode='', mode='', on_unknown='beep', on_action='keep', timeout=None, allow_fallback=(KeyFallbackType.shifted, KeyFallbackType.alternate)), definition='kitten hints --type linenum'),
|
||||
# open_selected_hyperlink
|
||||
KeyDefinition(is_sequence=True, trigger=SingleKey(mods=256, key=112), rest=(SingleKey(key=121),), options=KeyMapOptions(when_focus_on='', new_mode='', mode='', on_unknown='beep', on_action='keep', timeout=None, allow_fallback=(KeyFallbackType.shifted, KeyFallbackType.alternate)), definition='kitten hints --type hyperlink'),
|
||||
# restore_last_session
|
||||
KeyDefinition(trigger=SingleKey(mods=258, key=114), options=KeyMapOptions(when_focus_on='', new_mode='', mode='', on_unknown='beep', on_action='keep', timeout=None, allow_fallback=(KeyFallbackType.shifted, KeyFallbackType.alternate)), definition='restore_last_session'),
|
||||
# show_kitty_doc
|
||||
KeyDefinition(trigger=SingleKey(mods=256, key=57364), definition='show_kitty_doc overview'),
|
||||
# command_palette
|
||||
KeyDefinition(trigger=SingleKey(mods=256, key=57366), definition='command_palette'),
|
||||
# file_manager
|
||||
KeyDefinition(trigger=SingleKey(mods=5, key=101), definition='launch --type=window-dock --dock-edge=right --dock-size=60 kitten file-manager'),
|
||||
KeyDefinition(trigger=SingleKey(mods=5, key=101), definition='launch --type=window-dock --dock-edge=left --dock-size=60 kitten file-manager'),
|
||||
# toggle_fullscreen
|
||||
KeyDefinition(trigger=SingleKey(mods=256, key=57374), definition='toggle_fullscreen'),
|
||||
# toggle_maximized
|
||||
|
||||
+9
-1
@@ -327,7 +327,15 @@ def create_sessions(
|
||||
env_when_no_session: dict[str, str] | None = None,
|
||||
) -> Iterator[Session]:
|
||||
if args and args.session:
|
||||
if args.session == 'none':
|
||||
if args.session == 'last':
|
||||
from .session_restore import load_last_session, state_path
|
||||
|
||||
raw = load_last_session()
|
||||
if raw:
|
||||
yield from parse_session(raw, opts, session_arg='last', session_path=state_path())
|
||||
return
|
||||
log_error('There is no saved session to restore, starting a new session instead')
|
||||
elif args.session == 'none':
|
||||
default_session = 'none'
|
||||
else:
|
||||
session_arg = args.session
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPL v3 Copyright: 2026, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
# Keep the state of the session that was last in use so that `kitty --session=last` can restore it.
|
||||
#
|
||||
# The state is stored in the XDG state directory, is bounded in size and is only ever read when the
|
||||
# user explicitly asks for it, since restoring an unexpected state is worse than not restoring
|
||||
# anything. Anything that cannot be read back is discarded instead of preventing startup.
|
||||
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
from contextlib import suppress
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from .config import atomic_save
|
||||
from .utils import log_error
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .typing_compat import BossType
|
||||
|
||||
STATE_VERSION = 1
|
||||
MAX_STATE_SIZE = 1024 * 1024
|
||||
STATE_FILE_NAME = 'last-session.json'
|
||||
|
||||
|
||||
def state_dir() -> str:
|
||||
base = os.environ.get('XDG_STATE_HOME') or os.path.join(os.path.expanduser('~'), '.local', 'state')
|
||||
return os.path.join(base, 'kitty')
|
||||
|
||||
|
||||
def state_path() -> str:
|
||||
return os.path.join(state_dir(), STATE_FILE_NAME)
|
||||
|
||||
|
||||
def serialize_state(session: str, saved_at: float | None = None) -> bytes:
|
||||
state = {'version': STATE_VERSION, 'saved_at': time.time() if saved_at is None else saved_at, 'session': session}
|
||||
return json.dumps(state, ensure_ascii=False).encode('utf-8')
|
||||
|
||||
|
||||
def save_last_session(session: str) -> bool:
|
||||
"""Store the session text, returning False when it cannot be stored."""
|
||||
if not session.strip():
|
||||
return False
|
||||
if len(session) > MAX_STATE_SIZE:
|
||||
log_error(f'Not saving the last session as it is larger than {MAX_STATE_SIZE} characters, use save_as_session for large sessions')
|
||||
return False
|
||||
path = state_path()
|
||||
try:
|
||||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||
atomic_save(serialize_state(session), path)
|
||||
except OSError as e:
|
||||
log_error(f'Failed to save the last session to {path}: {e}')
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def prune_missing_directories(session: str) -> tuple[str, int]:
|
||||
"""Drop cd directives whose directory is gone, so that a stale state does not fail to restore."""
|
||||
lines: list[str] = []
|
||||
pruned = 0
|
||||
for line in session.splitlines():
|
||||
stripped = line.strip()
|
||||
if stripped.startswith('cd ') and stripped[3:].strip():
|
||||
raw = stripped[3:].strip().strip('"\'')
|
||||
path = os.path.expanduser(raw)
|
||||
if os.path.isabs(path) and not os.path.isdir(path):
|
||||
pruned += 1
|
||||
continue
|
||||
lines.append(line)
|
||||
return '\n'.join(lines), pruned
|
||||
|
||||
|
||||
def discard_last_session() -> None:
|
||||
try:
|
||||
os.remove(state_path())
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
except OSError as e:
|
||||
log_error(f'Failed to delete the unreadable last session: {e}')
|
||||
|
||||
|
||||
def parse_state(raw: bytes) -> str:
|
||||
try:
|
||||
parsed: Any = json.loads(raw)
|
||||
except (ValueError, UnicodeDecodeError) as e:
|
||||
raise ValueError(f'not valid JSON: {e}') from e
|
||||
if not isinstance(parsed, dict):
|
||||
raise ValueError('not a JSON object')
|
||||
version = parsed.get('version')
|
||||
if not isinstance(version, int):
|
||||
raise ValueError('missing state version')
|
||||
if version > STATE_VERSION:
|
||||
raise ValueError(f'state version {version} is newer than the supported version {STATE_VERSION}')
|
||||
session = parsed.get('session')
|
||||
if not isinstance(session, str):
|
||||
raise ValueError('missing session text')
|
||||
return session
|
||||
|
||||
|
||||
def load_last_session() -> str:
|
||||
"""Return the stored session text, or an empty string when there is nothing usable."""
|
||||
path = state_path()
|
||||
try:
|
||||
with open(path, 'rb') as f:
|
||||
raw = f.read(MAX_STATE_SIZE + 1)
|
||||
except FileNotFoundError:
|
||||
return ''
|
||||
except OSError as e:
|
||||
log_error(f'Failed to read the last session from {path}: {e}')
|
||||
return ''
|
||||
if len(raw) > MAX_STATE_SIZE:
|
||||
log_error(f'Discarding the last session in {path} as it is larger than {MAX_STATE_SIZE} bytes')
|
||||
discard_last_session()
|
||||
return ''
|
||||
try:
|
||||
session = parse_state(raw)
|
||||
except ValueError as e:
|
||||
log_error(f'Discarding the last session in {path} as it cannot be read: {e}')
|
||||
discard_last_session()
|
||||
return ''
|
||||
session, pruned = prune_missing_directories(session)
|
||||
if pruned:
|
||||
log_error(f'Dropped {pruned} working directory directive(s) from the last session as the directories no longer exist')
|
||||
return session
|
||||
|
||||
|
||||
def save_session_of(boss: 'BossType') -> None:
|
||||
"""Save the state of a running kitty instance, never raising so that it cannot break quitting."""
|
||||
from .session import default_save_as_session_opts
|
||||
|
||||
try:
|
||||
opts = default_save_as_session_opts()
|
||||
opts.os_window_geometry = True
|
||||
session = '\n'.join(boss.serialize_state_as_session('', opts))
|
||||
save_last_session(session)
|
||||
except Exception as e:
|
||||
log_error(f'Failed to save the last session: {e}')
|
||||
|
||||
|
||||
def restore_last_session_into(boss: 'BossType') -> bool:
|
||||
"""Add the tabs and windows of the last saved session to a running kitty.
|
||||
|
||||
Returns False when there is nothing to restore. The saved state is a JSON document, so it is
|
||||
handed to the session parser through a short lived file rather than duplicating the parsing.
|
||||
"""
|
||||
raw = load_last_session()
|
||||
if not raw:
|
||||
return False
|
||||
import tempfile
|
||||
|
||||
from .session import create_session
|
||||
|
||||
fd, path = tempfile.mkstemp(prefix='last-session-', suffix='.kitty-session')
|
||||
try:
|
||||
with open(fd, 'w', encoding='utf-8') as f:
|
||||
f.write(raw)
|
||||
create_session(boss, path)
|
||||
finally:
|
||||
with suppress(OSError):
|
||||
os.unlink(path)
|
||||
return True
|
||||
+101
-3
@@ -260,6 +260,17 @@ class TabAccessor:
|
||||
tab = get_boss().tab_for_id(self.tab_id)
|
||||
return os.path.basename((tab.get_exe_of_active_window(oldest=True) if tab else '') or '')
|
||||
|
||||
@property
|
||||
def active_wd_abbreviated(self) -> str:
|
||||
tab = get_boss().tab_for_id(self.tab_id)
|
||||
return abbreviate_path((tab.get_cwd_of_active_window() if tab else '') or '')
|
||||
|
||||
@property
|
||||
def last_cmd_exit_status(self) -> int:
|
||||
tab = get_boss().tab_for_id(self.tab_id)
|
||||
w = tab.active_window if tab else None
|
||||
return w.last_cmd_exit_status if w else 0
|
||||
|
||||
@property
|
||||
def last_focused_progress_percent(self) -> str:
|
||||
tab = get_boss().tab_for_id(self.tab_id)
|
||||
@@ -337,6 +348,10 @@ def template_uses_max_title_length(template: str) -> bool:
|
||||
# Not across updates, as templates can use state not in TabBarData, such as
|
||||
# the progress of the windows in the tab.
|
||||
title_cache: dict[tuple[DrawData, TabBarData, int, int], str] | None = None
|
||||
# Cells occupied by the close buttons drawn in the last layout pass, mapped to
|
||||
# the id of the tab they close. None while titles are being measured, so that
|
||||
# only the cells of the final drawing are kept.
|
||||
close_button_cells: dict[tuple[int, int], int] | None = None
|
||||
|
||||
|
||||
@contextmanager
|
||||
@@ -384,6 +399,7 @@ def evaluate_title_template(draw_data: DrawData, tab: TabBarData, index: int, ma
|
||||
ColorFormatter.draw_data = draw_data
|
||||
ColorFormatter.tab_data = tab
|
||||
boss = get_boss()
|
||||
last_cmd_exit_status = ta.last_cmd_exit_status
|
||||
eval_locals = {
|
||||
'index': index,
|
||||
'layout_name': tab.layout_name,
|
||||
@@ -400,6 +416,8 @@ def evaluate_title_template(draw_data: DrawData, tab: TabBarData, index: int, ma
|
||||
'bell_symbol': draw_data.bell_on_tab if tab.needs_attention else '',
|
||||
'secure_input_symbol': si,
|
||||
'activity_symbol': draw_data.tab_activity_symbol if tab.has_activity_since_last_focus else '',
|
||||
'last_exit_code': str(last_cmd_exit_status) if last_cmd_exit_status else '',
|
||||
'exit_status_symbol': exit_status_indicator(last_cmd_exit_status),
|
||||
'max_title_length': max_title_length,
|
||||
'keyboard_mode': boss.mappings.current_keyboard_mode_name,
|
||||
}
|
||||
@@ -407,7 +425,7 @@ def evaluate_title_template(draw_data: DrawData, tab: TabBarData, index: int, ma
|
||||
if tab.is_active and draw_data.active_title_template is not None:
|
||||
template = draw_data.active_title_template
|
||||
prefix = ''
|
||||
for default_prefix in ('bell_symbol', 'activity_symbol', 'secure_input_symbol'):
|
||||
for default_prefix in ('bell_symbol', 'activity_symbol', 'exit_status_symbol', 'secure_input_symbol'):
|
||||
if eval_locals[default_prefix] and not template_has_field(template, default_prefix):
|
||||
prefix += '{' + default_prefix + '}'
|
||||
if prefix:
|
||||
@@ -498,8 +516,65 @@ def truncate_line(line: str, width: int) -> str:
|
||||
return out + '…'
|
||||
|
||||
|
||||
def exit_status_indicator(exit_status: int) -> str:
|
||||
"""A short indicator for the exit status of the last command, empty on success."""
|
||||
return f'✘ {exit_status} ' if exit_status else ''
|
||||
|
||||
|
||||
def abbreviate_path(path: str, home: str | None = None, max_length: int = 0) -> str:
|
||||
"""Return a compact representation of path for use in a tab title.
|
||||
|
||||
The home directory is shown as ``~`` and the directories between it and
|
||||
the last component are reduced to their first character, so
|
||||
``~/projects/fws-kitty`` becomes ``~/p/fws-kitty``. When max_length is
|
||||
positive and the result is wider, the middle directories are replaced by
|
||||
an ellipsis, keeping the last component, which is the most informative
|
||||
part. Widths are measured in terminal cells.
|
||||
"""
|
||||
if not path:
|
||||
return ''
|
||||
home = os.path.normpath(home or os.path.expanduser('~'))
|
||||
p = os.path.normpath(path)
|
||||
if home and (p == home or p.startswith(home + os.sep)):
|
||||
prefix, rest = '~', p[len(home) :]
|
||||
elif p.startswith(os.sep):
|
||||
prefix, rest = os.sep, p
|
||||
else:
|
||||
prefix, rest = '', p
|
||||
components = [c for c in rest.split(os.sep) if c]
|
||||
if not components:
|
||||
return prefix or os.sep
|
||||
|
||||
def join(parts: Sequence[str]) -> str:
|
||||
if prefix == os.sep:
|
||||
return os.sep + os.sep.join(parts)
|
||||
if prefix == '~':
|
||||
return '~' + (os.sep + os.sep.join(parts) if parts else '')
|
||||
return os.sep.join(parts)
|
||||
|
||||
ans = join([c[0] for c in components[:-1]] + [components[-1]])
|
||||
if max_length > 0 and wcswidth(ans) > max_length:
|
||||
last = components[-1]
|
||||
marker = prefix + os.sep + '…' if prefix else '…'
|
||||
for candidate in (marker + os.sep + last, '…' + os.sep + last if prefix else last):
|
||||
if wcswidth(candidate) <= max_length:
|
||||
return candidate
|
||||
# Even the last component alone is too wide, keep its end as that is
|
||||
# the part that distinguishes it from its siblings.
|
||||
available = max_length - wcswidth(marker) - 1
|
||||
if available > 0:
|
||||
return marker + os.sep + truncate_line(last, available)
|
||||
return truncate_line(ans, max_length)
|
||||
return ans
|
||||
|
||||
|
||||
def draw_title(draw_data: DrawData, screen: Screen, tab: TabBarData, index: int, max_title_length: int = 0) -> None:
|
||||
title = apply_title_template(draw_data, tab, index, max_title_length)
|
||||
# Close buttons live in horizontal tab bars, where there is a spare cell at
|
||||
# the start of each tab. Vertical tabs are already crowded and their titles
|
||||
# wrap, so they keep closing with the middle mouse button.
|
||||
show_close = tab.tab_id > 0 and draw_data.tab_bar_edge in ('top', 'bottom') and (max_title_length <= 0 or max_title_length >= 3)
|
||||
title_width = max(1, max_title_length - 2) if show_close and max_title_length > 0 else max_title_length
|
||||
title = apply_title_template(draw_data, tab, index, title_width)
|
||||
if draw_data.max_tab_title_lines > 1 and draw_data.wrap_width:
|
||||
title = wrap_title(title, draw_data.wrap_width)
|
||||
if '\n' in title:
|
||||
@@ -511,9 +586,14 @@ def draw_title(draw_data: DrawData, screen: Screen, tab: TabBarData, index: int,
|
||||
# Mark the truncation, since the caller's ellipsis logic only fires
|
||||
# when the final line reaches the full width of the tab.
|
||||
del lines[limit:]
|
||||
lines[-1] = truncate_line(lines[-1], draw_data.wrap_width or max_title_length)
|
||||
lines[-1] = truncate_line(lines[-1], draw_data.wrap_width or title_width)
|
||||
title = '\n'.join(lines)
|
||||
before_draw = screen.cursor.x
|
||||
if show_close:
|
||||
if close_button_cells is not None:
|
||||
close_button_cells[(before_draw, screen.cursor.y)] = tab.tab_id
|
||||
close_button_cells[(before_draw + 1, screen.cursor.y)] = tab.tab_id
|
||||
screen.draw('× ')
|
||||
draw_attributed_string(title, screen)
|
||||
if draw_data.max_tab_title_length > 0:
|
||||
x_limit = before_draw + draw_data.max_tab_title_length
|
||||
@@ -811,6 +891,7 @@ class TabBar:
|
||||
self.data_buffer_size = 0
|
||||
self.blank_rects: tuple[Border, ...] = ()
|
||||
self.tab_extents: Sequence[TabExtent] = ()
|
||||
self.close_button_cells: dict[tuple[int, int], int] = {}
|
||||
self.window_drop_insert_before: int | None = None
|
||||
self.tab_drop_insert_before: int | None = None
|
||||
self.laid_out_once = False
|
||||
@@ -996,6 +1077,7 @@ class TabBar:
|
||||
self.blank_rects = tuple(blank_rects)
|
||||
|
||||
def layout(self) -> None:
|
||||
self.close_button_cells = {}
|
||||
central, tab_bar, vw, vh, cell_width, cell_height = viewport_for_window(self.os_window_id)
|
||||
if self.is_vertical:
|
||||
if tab_bar.width < cell_width or tab_bar.height < cell_height:
|
||||
@@ -1149,11 +1231,15 @@ class TabBar:
|
||||
s.erase_in_line(2, False)
|
||||
cr: list[TabExtent] = []
|
||||
ed.for_layout = False
|
||||
global close_button_cells
|
||||
close_button_cells = {}
|
||||
for i, t in enumerate(data):
|
||||
try:
|
||||
draw_tab(i, t, cr, max_tab_lengths[i])
|
||||
except StopIteration:
|
||||
break
|
||||
self.close_button_cells = close_button_cells
|
||||
close_button_cells = None
|
||||
self.tab_extents = cr
|
||||
s.erase_in_line(0, False) # Ensure no long titles bleed after the last tab
|
||||
self.align()
|
||||
@@ -1164,6 +1250,7 @@ class TabBar:
|
||||
s = self.screen
|
||||
self.last_laid_out_tabs = data
|
||||
self.tab_extents = ()
|
||||
self.close_button_cells = {}
|
||||
s.cursor.x = s.cursor.y = 0
|
||||
s.erase_in_display(2, False)
|
||||
if not data:
|
||||
@@ -1312,6 +1399,17 @@ class TabBar:
|
||||
return te.tab_id
|
||||
return 0
|
||||
|
||||
def close_tab_id_at(self, x: int, y: int) -> int:
|
||||
"The id of the tab whose close button is at the specified pixel, or zero."
|
||||
if not self.laid_out_once or not self.close_button_cells:
|
||||
return 0
|
||||
g = self.window_geometry
|
||||
if not (g.left <= x < g.right and g.top <= y < g.bottom):
|
||||
return 0
|
||||
x = (x - g.left) // self.cell_width
|
||||
y = (y - g.top) // self.cell_height
|
||||
return self.close_button_cells.get((x, y), 0)
|
||||
|
||||
def drag_axis_coordinate(self, x: int, y: int) -> int:
|
||||
return y if self.is_vertical else x
|
||||
|
||||
|
||||
@@ -2093,9 +2093,19 @@ class TabManager: # {{{
|
||||
self.recent_tab_bar_mouse_events.clear()
|
||||
return
|
||||
if button == GLFW_MOUSE_BUTTON_LEFT:
|
||||
close_tab_id = self.tab_bar.close_tab_id_at(int(x), int(y))
|
||||
if action == GLFW_PRESS:
|
||||
if close_tab_id:
|
||||
return # clicking the close button must not start a drag
|
||||
set_tab_being_dragged(tab.id, False, x, y)
|
||||
return
|
||||
if close_tab_id:
|
||||
if self.recent_tab_bar_mouse_events.click_count(GLFW_MOUSE_BUTTON_LEFT) == 1:
|
||||
set_tab_being_dragged()
|
||||
self.recent_tab_bar_mouse_events.clear()
|
||||
if (tab_to_close := self.tab_for_id(close_tab_id)) is not None:
|
||||
get_boss().close_tab(tab_to_close)
|
||||
return
|
||||
match self.recent_tab_bar_mouse_events.click_count(GLFW_MOUSE_BUTTON_LEFT):
|
||||
case 2:
|
||||
self.set_active_tab(tab)
|
||||
|
||||
@@ -2056,6 +2056,8 @@ class Window:
|
||||
self.last_cmd_exit_status = int(exit_status)
|
||||
except Exception:
|
||||
self.last_cmd_exit_status = 0
|
||||
if (tab := self.tabref()) is not None:
|
||||
tab.mark_tab_bar_dirty()
|
||||
end_time = monotonic()
|
||||
last_cmd_output_duration = end_time - self.last_cmd_output_start_time
|
||||
self.last_cmd_output_start_time = 0.0
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPL v3 Copyright: 2026, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import tempfile
|
||||
from unittest.mock import patch
|
||||
|
||||
from kitty.config import load_config
|
||||
from kitty.session import create_sessions, parse_session
|
||||
from kitty.session_restore import (
|
||||
MAX_STATE_SIZE,
|
||||
discard_last_session,
|
||||
load_last_session,
|
||||
prune_missing_directories,
|
||||
save_last_session,
|
||||
state_path,
|
||||
)
|
||||
from kitty.utils import log_error
|
||||
|
||||
from .base import BaseTest
|
||||
|
||||
|
||||
class TestSessionRestore(BaseTest):
|
||||
def setUp(self) -> None:
|
||||
super().setUp()
|
||||
self.tdir = tempfile.mkdtemp()
|
||||
self.env_patch = patch.dict(os.environ, {'XDG_STATE_HOME': self.tdir})
|
||||
self.env_patch.start()
|
||||
self.error_messages: list[str] = []
|
||||
log_error.redirect = self.error_messages.append
|
||||
|
||||
def tearDown(self) -> None:
|
||||
del log_error.redirect
|
||||
self.env_patch.stop()
|
||||
shutil.rmtree(self.tdir)
|
||||
super().tearDown()
|
||||
|
||||
def write_state(self, data: bytes) -> None:
|
||||
os.makedirs(os.path.dirname(state_path()), exist_ok=True)
|
||||
with open(state_path(), 'wb') as f:
|
||||
f.write(data)
|
||||
|
||||
def test_state_lives_in_the_xdg_state_directory(self) -> None:
|
||||
self.ae(state_path(), os.path.join(self.tdir, 'kitty', 'last-session.json'))
|
||||
|
||||
def test_roundtrip(self) -> None:
|
||||
session = 'new_tab work\nlayout tall\ncd /tmp\nlaunch --title editor\nlaunch'
|
||||
self.assertTrue(save_last_session(session))
|
||||
self.assertTrue(os.path.exists(state_path()))
|
||||
self.ae(load_last_session(), session)
|
||||
|
||||
def test_nothing_is_saved_for_an_empty_session(self) -> None:
|
||||
self.assertFalse(save_last_session(' \n'))
|
||||
self.ae(load_last_session(), '')
|
||||
|
||||
def test_missing_state_is_not_an_error(self) -> None:
|
||||
self.ae(load_last_session(), '')
|
||||
self.ae(self.error_messages, [])
|
||||
|
||||
def test_too_large_state_is_neither_saved_nor_restored(self) -> None:
|
||||
self.assertFalse(save_last_session('x' * (MAX_STATE_SIZE + 1)))
|
||||
self.assertFalse(os.path.exists(state_path()))
|
||||
self.write_state(json.dumps({'version': 1, 'session': 'x' * (MAX_STATE_SIZE + 1)}).encode())
|
||||
self.ae(load_last_session(), '')
|
||||
self.assertFalse(os.path.exists(state_path()))
|
||||
self.assertTrue(self.error_messages)
|
||||
|
||||
def test_corrupt_state_is_discarded(self) -> None:
|
||||
self.write_state(b'{"version": 1, "session": ')
|
||||
self.ae(load_last_session(), '')
|
||||
self.assertFalse(os.path.exists(state_path()))
|
||||
self.assertTrue(any('cannot be read' in msg for msg in self.error_messages))
|
||||
|
||||
def test_newer_state_version_is_discarded(self) -> None:
|
||||
self.write_state(json.dumps({'version': 99, 'session': 'launch'}).encode())
|
||||
self.ae(load_last_session(), '')
|
||||
self.assertFalse(os.path.exists(state_path()))
|
||||
|
||||
def test_missing_or_invalid_fields_are_discarded(self) -> None:
|
||||
for data in ({}, {'version': 1}, {'session': 'launch'}, {'version': '1', 'session': 'launch'}, []):
|
||||
self.write_state(json.dumps(data).encode())
|
||||
self.ae(load_last_session(), '', data)
|
||||
self.assertFalse(os.path.exists(state_path()), data)
|
||||
self.assertFalse(os.path.exists(state_path()))
|
||||
|
||||
def test_discard_is_idempotent(self) -> None:
|
||||
discard_last_session()
|
||||
self.ae(self.error_messages, [])
|
||||
|
||||
def test_stale_directories_are_pruned(self) -> None:
|
||||
missing = os.path.join(self.tdir, 'gone')
|
||||
session = f'new_tab a\ncd {missing}\nlaunch\nnew_tab b\ncd {self.tdir}\nlaunch'
|
||||
session, pruned = prune_missing_directories(session)
|
||||
self.ae(pruned, 1)
|
||||
self.assertNotIn(missing, session)
|
||||
self.assertIn(f'cd {self.tdir}', session)
|
||||
self.assertIn('new_tab b', session)
|
||||
self.assertTrue(self.error_messages == []) # pruning itself does not log
|
||||
|
||||
def test_pruning_is_applied_when_loading(self) -> None:
|
||||
missing = os.path.join(self.tdir, 'gone')
|
||||
self.assertTrue(save_last_session(f'cd {missing}\nlaunch'))
|
||||
self.ae(load_last_session(), 'launch')
|
||||
self.assertTrue(any('no longer exist' in msg for msg in self.error_messages))
|
||||
|
||||
def test_saved_state_is_a_valid_session(self) -> None:
|
||||
session = 'new_tab one\nlayout tall\nlaunch\nnew_tab two\nlaunch'
|
||||
self.assertTrue(save_last_session(session))
|
||||
opts = load_config()
|
||||
sessions = tuple(parse_session(load_last_session(), opts, session_arg='last', session_path=state_path()))
|
||||
self.ae(len(sessions), 1)
|
||||
self.ae(sessions[0].session_name, 'last')
|
||||
self.ae([t.name for t in sessions[0].tabs], ['one', 'two'])
|
||||
|
||||
def test_restore_is_explicit_on_the_command_line(self) -> None:
|
||||
from kitty.cli import parse_args
|
||||
|
||||
self.assertTrue(save_last_session('launch'))
|
||||
opts = load_config()
|
||||
args, rest = parse_args(['--session', 'last'])
|
||||
args.args = [] # type: ignore
|
||||
self.ae(args.session, 'last')
|
||||
self.ae(rest, [])
|
||||
sessions = tuple(create_sessions(opts, args))
|
||||
self.ae(len(sessions), 1)
|
||||
self.ae(sessions[0].session_name, 'last')
|
||||
self.ae(len(sessions[0].tabs[0].windows), 1)
|
||||
|
||||
def test_missing_state_falls_back_to_a_fresh_session(self) -> None:
|
||||
from kitty.cli import parse_args
|
||||
|
||||
opts = load_config()
|
||||
args, rest = parse_args(['--session', 'last'])
|
||||
args.args = [] # type: ignore
|
||||
sessions = tuple(create_sessions(opts, args))
|
||||
self.ae(len(sessions), 1)
|
||||
self.ae(sessions[0].session_name, '')
|
||||
self.assertTrue(any('no saved session' in msg for msg in self.error_messages))
|
||||
|
||||
def test_restore_action_without_state_returns_false(self) -> None:
|
||||
from kitty.session_restore import restore_last_session_into
|
||||
|
||||
self.assertFalse(restore_last_session_into(None)) # type: ignore
|
||||
+90
-9
@@ -1,11 +1,27 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPL v3 Copyright: 2026, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
import os
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
from kitty.fast_data_types import LEFT_EDGE, Color, Region, Screen
|
||||
from kitty.options.utils import tab_title_wrap
|
||||
from kitty.tab_bar import CellRange, DrawData, ExtraData, TabBar, TabBarData, TabExtent, WindowDropTarget, as_rgb, powerline_symbols, truncate_line, wrap_title
|
||||
from kitty.tab_bar import (
|
||||
CellRange,
|
||||
DrawData,
|
||||
ExtraData,
|
||||
TabBar,
|
||||
TabBarData,
|
||||
TabExtent,
|
||||
WindowDropTarget,
|
||||
abbreviate_path,
|
||||
as_rgb,
|
||||
exit_status_indicator,
|
||||
powerline_symbols,
|
||||
truncate_line,
|
||||
wrap_title,
|
||||
)
|
||||
from kitty.utils import color_as_int
|
||||
|
||||
from .base import BaseTest
|
||||
@@ -392,6 +408,47 @@ class TestTabBar(BaseTest):
|
||||
# empty line still gets ellipsis
|
||||
self.ae(truncate_line('', 4), '…')
|
||||
|
||||
def test_abbreviate_path(self) -> None:
|
||||
self.ae(abbreviate_path(''), '')
|
||||
self.ae(abbreviate_path('/home/user/projects/fws-kitty', '/home/user'), '~/p/fws-kitty')
|
||||
# the home directory itself has no component to abbreviate
|
||||
self.ae(abbreviate_path('/home/user', '/home/user'), '~')
|
||||
self.ae(abbreviate_path('/home/user/', '/home/user'), '~')
|
||||
# a trailing slash does not add an empty component
|
||||
self.ae(abbreviate_path('/usr/local/bin/'), '/u/l/bin')
|
||||
self.ae(abbreviate_path('/'), '/')
|
||||
self.ae(abbreviate_path('some/relative/dir'), 's/r/dir')
|
||||
# the last component is never abbreviated, it is the most informative
|
||||
self.ae(abbreviate_path('/home/user/a/very-long-project', '/home/user'), '~/a/very-long-project')
|
||||
# when the result is too wide, middle directories are elided rather
|
||||
# than cutting off the end of the title
|
||||
self.ae(abbreviate_path('/home/user/one/two/three/project', '/home/user', 14), '~/…/project')
|
||||
# when even that is too wide, the last component is truncated too
|
||||
self.ae(abbreviate_path('/home/user/a/very-long-final-dir', '/home/user', 12), '~/…/very-lo…')
|
||||
# widths are measured in terminal cells, so wide characters count double
|
||||
self.ae(abbreviate_path('/日本語/東京'), '/日/東京')
|
||||
|
||||
def test_exit_status_indicator(self) -> None:
|
||||
self.ae(exit_status_indicator(0), '')
|
||||
self.ae(exit_status_indicator(1), '✘ 1 ')
|
||||
self.ae(exit_status_indicator(130), '✘ 130 ')
|
||||
|
||||
def test_tab_title_indicators(self) -> None:
|
||||
home = os.path.expanduser('~')
|
||||
fake_tab = SimpleNamespace(
|
||||
active_window=SimpleNamespace(last_cmd_exit_status=127),
|
||||
get_cwd_of_active_window=lambda oldest=False: os.path.join(home, 'projects', 'fws-kitty'),
|
||||
)
|
||||
boss = SimpleNamespace(tab_for_id=lambda tab_id: fake_tab, mappings=SimpleNamespace(current_keyboard_mode_name=''))
|
||||
line = self.horizontal_tab_bar_line(
|
||||
['ignored'],
|
||||
60,
|
||||
boss=boss,
|
||||
tab_bar_style='separator',
|
||||
tab_title_template='{last_exit_code}:{exit_status_symbol}{tab.active_wd_abbreviated}',
|
||||
)
|
||||
self.assertIn('127:✘ 127 ~/p/fws-kitty', line)
|
||||
|
||||
def test_tab_title_wrap_option(self) -> None:
|
||||
for off in ('no', 'No', 'n', 'false', 'none', '0'):
|
||||
self.ae(tab_title_wrap(off), 0)
|
||||
@@ -601,7 +658,7 @@ class TestTabBar(BaseTest):
|
||||
[f' t0 {separator}', f'abcdefghijk{separator}', f'x {separator}'],
|
||||
)
|
||||
|
||||
def horizontal_tab_bar_line(self, titles: list[str], columns: int, **opts: object) -> str:
|
||||
def horizontal_tab_bar(self, titles: list[str], columns: int, boss: object | None = None, **opts: object) -> TabBar:
|
||||
self.set_options({'tab_title_template': '{title}', **opts})
|
||||
central = region(0, 0, columns * 10, 180)
|
||||
tab_bar = region(0, 180, columns * 10, 200)
|
||||
@@ -610,24 +667,48 @@ class TestTabBar(BaseTest):
|
||||
patch('kitty.tab_bar.viewport_for_window', return_value=(central, tab_bar, columns * 10, 200, 10, 20)),
|
||||
patch('kitty.tab_bar.set_tab_bar_render_data'),
|
||||
patch('kitty.tab_bar.update_tab_bar_edge_colors', return_value=None),
|
||||
patch('kitty.tab_bar.get_boss', return_value=DummyBoss()),
|
||||
patch('kitty.tab_bar.get_boss', return_value=boss if boss is not None else DummyBoss()),
|
||||
):
|
||||
tb = TabBar(1)
|
||||
tb.layout()
|
||||
tb.update(tuple(TabBarData(title=t, tab_id=i + 1, is_active=i == 0) for i, t in enumerate(titles)))
|
||||
return str(tb.screen.line(0)).rstrip()
|
||||
return tb
|
||||
|
||||
def horizontal_tab_bar_line(self, titles: list[str], columns: int, boss: object | None = None, **opts: object) -> str:
|
||||
return str(self.horizontal_tab_bar(titles, columns, boss, **opts).screen.line(0)).rstrip()
|
||||
|
||||
def test_horizontal_tab_bar_close_buttons(self) -> None:
|
||||
tb = self.horizontal_tab_bar(['one', 'two'], 40, tab_bar_style='separator')
|
||||
line = str(tb.screen.line(0))
|
||||
self.ae(line.count('×'), 2)
|
||||
# each close button is two cells wide, at the start of its tab
|
||||
self.ae(set(tb.close_button_cells.values()), {1, 2})
|
||||
for (cell_x, row), tab_id in tb.close_button_cells.items():
|
||||
px = tb.window_geometry.left + cell_x * tb.cell_width + 1
|
||||
py = tb.window_geometry.top + row * tb.cell_height + 1
|
||||
self.ae(tb.close_tab_id_at(px, py), tab_id)
|
||||
# clicking the title itself does not close the tab
|
||||
for te in tb.tab_extents:
|
||||
px = tb.window_geometry.left + te.x.end * tb.cell_width
|
||||
py = tb.window_geometry.top + 1
|
||||
self.ae(tb.close_tab_id_at(px, py), 0)
|
||||
self.ae(tb.close_tab_id_at(0, 0), 0)
|
||||
|
||||
# vertical tab bars keep closing with the middle mouse button
|
||||
self.ae(self.vertical_tab_bar().close_button_cells, {})
|
||||
|
||||
def test_horizontal_tab_bar_uses_free_space(self) -> None:
|
||||
line = self.horizontal_tab_bar_line
|
||||
# space not needed by short tabs goes to the long ones, instead of
|
||||
# being left unused at the end of the tab bar
|
||||
long_title = 'abcdefghijklmn'
|
||||
# two extra cells per tab are needed for its close button
|
||||
for style, columns, titles in (
|
||||
('fade', 25, ['1', long_title]),
|
||||
('fade', 35, ['1'] * 2 + [long_title]),
|
||||
('separator', 60, ['1'] * 8 + [long_title] * 2),
|
||||
('powerline', 80, ['1'] * 5 + [long_title] * 3),
|
||||
('slant', 126, ['1'] * 9 + [long_title] * 4),
|
||||
('fade', 29, ['1', long_title]),
|
||||
('fade', 41, ['1'] * 2 + [long_title]),
|
||||
('separator', 80, ['1'] * 8 + [long_title] * 2),
|
||||
('powerline', 96, ['1'] * 5 + [long_title] * 3),
|
||||
('slant', 152, ['1'] * 9 + [long_title] * 4),
|
||||
):
|
||||
text = line(titles, columns, tab_bar_style=style)
|
||||
self.ae(text.count(long_title), titles.count(long_title), (style, text))
|
||||
|
||||
Reference in new issue
Block a user