From 1b330bcf81234ce23914c2ffeb131848098fffa0 Mon Sep 17 00:00:00 2001 From: BlackAngelTVdev Date: Wed, 11 Nov 2026 08:20:11 +0100 Subject: [PATCH 1/3] feat(file-manager): sync the working directory with the shell The panel and the shell each kept their own directory. The new sync_cwd option keeps them in step both ways, through files in a session directory exported by kitty rather than by typing a command into the terminal: the shell applies the directory chosen in the panel from its prompt hook with builtin cd, so nothing lands in the history and a half typed multi-line command is not submitted. --- docs/changelog.rst | 7 ++ docs/glossary.rst | 15 ++- docs/kittens/file-manager.rst | 45 +++++++- kittens/file_manager/main.go | 47 +++++++- kittens/file_manager/main.py | 25 +++++ kittens/file_manager/sync.go | 85 +++++++++++++++ kittens/file_manager/sync_test.go | 100 ++++++++++++++++++ kitty/child.py | 16 +++ kitty/tabs.py | 11 ++ shell-integration/bash/kitty.bash | 33 +++++- .../kitty-shell-integration.fish | 22 ++++ shell-integration/zsh/kitty-integration | 25 +++++ 12 files changed, 425 insertions(+), 6 deletions(-) create mode 100644 kittens/file_manager/sync.go create mode 100644 kittens/file_manager/sync_test.go diff --git a/docs/changelog.rst b/docs/changelog.rst index 9b5d2fe..792a045 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -222,6 +222,13 @@ Detailed list of changes 0.50.1 [unreleased] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +- The :doc:`file manager ` can now keep its directory in + step with the shell: with :code:`sync_cwd yes`, a :code:`cd` moves the panel + into the same directory and validating a directory moves the shell at its + next prompt, for bash, zsh and fish. Nothing is typed into the terminal, so + no command lands in the history and a multi-line command being typed is left + untouched. + - :kbd:`Ctrl+Shift+E` now opens the :doc:`file manager kitten ` in a left dock by default, instead of requiring a manual mapping. This takes the key over from :ac:`open_url`; remap diff --git a/docs/glossary.rst b/docs/glossary.rst index 66c1411..bda4943 100644 --- a/docs/glossary.rst +++ b/docs/glossary.rst @@ -181,11 +181,24 @@ Variables que kitty définit en lançant des programmes enfants fonctions appelant :program:`kitty` fonctionnent correctement. .. envvar:: KITTY_WINDOW_ID - Un entier qui est l'identifiant de la :term:`fenêtre ` kitty dans laquelle le programme s'exécute. Utilisable avec la :doc:`facilité de contrôle à distance de kitty `. +.. envvar:: KITTY_CWD_SYNC_DIR + + Le répertoire de session dans lequel les shells et les kittens qui coopèrent + échangent leur répertoire courant, voir la :ref:`synchronisation du + gestionnaire de fichiers `. Il n'est lisible que par votre + utilisateur et disparaît à la fin de la session. + +.. envvar:: KITTY_SPECIAL_WINDOW_PARENT + + Un entier qui est l'identifiant de la :term:`fenêtre ` pour laquelle + une fenêtre spéciale (overlay ou dock) a été ouverte. Absent des fenêtres + normales ; le :doc:`gestionnaire de fichiers ` s'en + sert pour retrouver le shell dont il suit le répertoire. + .. envvar:: KITTY_PID Un entier qui est l'identifiant du processus kitty dans lequel le programme diff --git a/docs/kittens/file-manager.rst b/docs/kittens/file-manager.rst index 86f1404..efb6f95 100644 --- a/docs/kittens/file-manager.rst +++ b/docs/kittens/file-manager.rst @@ -32,8 +32,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, sauf si la synchronisation décrite plus bas + est activée : le dock suit alors la fenêtre active du groupe au moment de sa + création. L'ouverture d'un fichier, elle, fonctionne partout : le panneau confie le fichier à kitty, qui lance l'éditeur dans un nouvel onglet. Le fichier @@ -94,6 +95,46 @@ Actions ferme le panneau sans rien changer. +Synchronisation avec le shell +------------------------------ + +Par défaut, le panneau et le shell gardent chacun leur répertoire : le panneau +part de celui du shell, mais un :code:`cd` d'un côté ne change rien de l'autre. +L'option ``sync_cwd`` les tient synchronisés dans les deux sens :: + + # ~/.config/kitty/file-manager.conf + sync_cwd yes + +Un :code:`cd` dans le shell amène alors le panneau dans le même répertoire, et +valider un répertoire dans le panneau amène le shell vers celui-ci. + +L'échange ne passe pas par le terminal. kitty exporte un répertoire de session +dans :envvar:`KITTY_CWD_SYNC_DIR` ; le shell y publie son répertoire courant et +le panneau y dépose celui qu'il veut. Le panneau retrouve le shell qui l'a lancé +grâce à :envvar:`KITTY_SPECIAL_WINDOW_PARENT`. L'intégration shell de kitty, pour +bash, zsh et fish, applique la demande avec :code:`builtin cd` : aucune commande +n'entre dans l'historique et une commande multi-lignes en cours de saisie n'est +pas soumise. + +.. note:: + + La synchronisation demande l'intégration shell de kitty, active par défaut + pour bash, zsh et fish. Les autres shells gardent le comportement précédent : + le panneau retape la commande :code:`cd` dans le terminal, comme lorsque + l'option est désactivée. + + Le changement est appliqué au prompt suivant : le shell se déplace quand la + commande suivante démarre, ou qu'une ligne vide est validée, et non à + l'instant où le panneau se ferme. C'est le prix à payer pour ne jamais écrire + dans le terminal. + + Lancé dans un dock, le panneau suit la fenêtre active du groupe au moment où + le dock est créé. Si vous passez ensuite à une autre fenêtre du même groupe, + il continue de suivre cette première fenêtre : relancez le dock pour changer + de cible. Dans un panneau du bureau, il n'y a pas de shell à suivre et la + synchronisation reste inerte. + + .. _file-manager-shortcuts: Raccourcis et configuration diff --git a/kittens/file_manager/main.go b/kittens/file_manager/main.go index 89f6720..645bc11 100644 --- a/kittens/file_manager/main.go +++ b/kittens/file_manager/main.go @@ -204,6 +204,8 @@ type Handler struct { result_path string shortcut_tracker config.ShortcutTracker keyboard_shortcuts []*config.KeyAction + sync *shell_sync + sync_handled bool } func (h *Handler) initialize() (string, error) { @@ -218,11 +220,43 @@ func (h *Handler) initialize() (string, error) { if err = h.load(h.cwd); err != nil { return "", err } + if h.sync != nil { + // Adopt the directory the shell is already in as the reference point so + // that an explicit --start-dir is not overridden by the first tick. + h.sync.last = h.sync.shell_cwd() + if _, err = h.lp.AddTimer(400*time.Millisecond, true, func(loop.IdType) error { + h.follow_shell_cwd() + return nil + }); err != nil { + return "", err + } + } h.draw_screen() h.lp.SendOverlayReady() return "", nil } +// follow_shell_cwd mirrors a cd made in the shell into the panel, keeping the +// selection on the same name so that the cursor does not jump around. +func (h *Handler) follow_shell_cwd() { + if h.sync == nil { + return + } + dir := h.sync.new_target(h.cwd) + if dir == "" { + return + } + name := "" + if e, ok := h.selected_entry(); ok { + name = e.Name + } + if err := h.load(dir); err != nil { + return + } + h.select_name(name) + h.draw_screen() +} + // load reads dir and adopts it as the current directory. Selection is clamped // rather than reset so that reloading a directory after an action keeps the // cursor near where it was. @@ -459,6 +493,11 @@ func (h *Handler) enter_dir() { func (h *Handler) change_shell_dir_to(path string) { h.result_action, h.result_path = "cd", path + // With the sync on, the shell reads the request from its session file at the + // next prompt, so the handler must not also type the change into its pty. + if h.sync != nil && h.sync.publish_request(path) == nil { + h.sync_handled = true + } h.lp.Quit(0) } @@ -776,7 +815,11 @@ func (h *Handler) draw_screen() { // result_payload is the JSON data handed over to the Python result handler. func (h *Handler) result_payload() map[string]string { - return map[string]string{"action": h.result_action, "path": h.result_path} + ans := map[string]string{"action": h.result_action, "path": h.result_path} + if h.sync_handled { + ans["sync"] = "1" + } + return ans } func load_config(opts *Options) (*Config, error) { @@ -805,7 +848,7 @@ func main(_ *cli.Command, opts *Options, args []string) (rc int, err error) { if err != nil { return 1, err } - h := &Handler{lp: lp, conf: conf, cwd: start_dir, show_hidden: opts.ShowHidden || conf.Show_hidden} + h := &Handler{lp: lp, conf: conf, cwd: start_dir, show_hidden: opts.ShowHidden || conf.Show_hidden, sync: new_shell_sync_from_env(conf.Sync_cwd)} h.keyboard_shortcuts = config.ResolveShortcuts(conf.KeyboardShortcuts) lp.MouseTrackingMode(loop.FULL_MOUSE_TRACKING) diff --git a/kittens/file_manager/main.py b/kittens/file_manager/main.py index e45d009..9d34c21 100644 --- a/kittens/file_manager/main.py +++ b/kittens/file_manager/main.py @@ -47,6 +47,27 @@ sorted by last modification time, most recent first. egr() +agr('shell', 'Shell synchronisation') + +opt( + 'sync_cwd', + 'no', + option_type='to_bool', + long_text=""" +Keep the shell's working directory and the panel in step. A :code:`cd` in the +shell moves the panel to the same directory, and validating a directory in the +panel makes the shell change to it at its next prompt. + +The exchange goes through two small files in the session directory kitty +exports as :envvar:`KITTY_CWD_SYNC_DIR`, so nothing is typed into the shell: +the command never lands in the history and a half typed multi-line command is +left untouched. Bash, zsh and fish are supported by their kitty shell +integration; other shells keep the current behaviour. +""", +) + +egr() + agr('opening', 'Opening files') opt( @@ -196,6 +217,10 @@ def handle_result(args: list[str], data: dict[str, Any], target_window_id: int, action, path = data.get('action'), data.get('path') if action != 'cd' or not path: return + if data.get('sync'): + # The panel published the directory in the session file and the shell + # picks it up from its prompt hook, see the sync_cwd option. + return w = boss.window_id_map.get(target_window_id) if w is None: boss.ring_bell_if_allowed() diff --git a/kittens/file_manager/sync.go b/kittens/file_manager/sync.go new file mode 100644 index 0000000..5361687 --- /dev/null +++ b/kittens/file_manager/sync.go @@ -0,0 +1,85 @@ +// License: GPLv3 Copyright: 2026, FWS + +package file_manager + +import ( + "os" + "path/filepath" + "strings" +) + +// shell_sync is the file based channel between a shell and the panel. kitty +// exports KITTY_CWD_SYNC_DIR to every window and KITTY_SPECIAL_WINDOW_PARENT to +// the special windows it opens for another one, so both sides agree on two file +// names without a socket or a new protocol: the shell publishes its working +// directory in /, the panel publishes the directory it wants in +// /.set. The shell applies that request from its prompt hook, +// which keeps the command out of the history and leaves a half typed multi-line +// command alone. +type shell_sync struct { + dir string + window_id string + last string +} + +func new_shell_sync(dir, window_id string, enabled bool) *shell_sync { + if !enabled || dir == "" || window_id == "" { + return nil + } + if info, err := os.Stat(dir); err != nil || !info.IsDir() { + return nil + } + return &shell_sync{dir: dir, window_id: window_id} +} + +// new_shell_sync_from_env is nil whenever the option is off or kitty did not +// give the panel a shell window to talk to, in which case the panel keeps its +// own behaviour and types the change into the shell instead. +func new_shell_sync_from_env(enabled bool) *shell_sync { + return new_shell_sync(os.Getenv("KITTY_CWD_SYNC_DIR"), os.Getenv("KITTY_SPECIAL_WINDOW_PARENT"), enabled) +} + +func (s *shell_sync) shell_cwd_path() string { return filepath.Join(s.dir, s.window_id) } +func (s *shell_sync) request_path() string { return s.shell_cwd_path() + ".set" } + +// shell_cwd returns the working directory last published by the shell. An empty +// or relative path, or one that no longer exists, is treated as unknown rather +// than followed, as the shell may be between two writes. +func (s *shell_sync) shell_cwd() string { + b, err := os.ReadFile(s.shell_cwd_path()) + if err != nil { + return "" + } + p := strings.TrimSpace(string(b)) + if !filepath.IsAbs(p) { + return "" + } + if info, err := os.Stat(p); err != nil || !info.IsDir() { + return "" + } + return p +} + +// new_target returns the directory the panel should move to, or "" when the +// shell has not moved since the last call or already sits in current. +func (s *shell_sync) new_target(current string) string { + p := s.shell_cwd() + if p == "" || p == s.last { + return "" + } + s.last = p + if p == current { + return "" + } + return p +} + +// publish_request hands a directory to the shell. The write goes through a +// temporary file so that the shell never reads a half written path. +func (s *shell_sync) publish_request(dir string) error { + tmp := s.request_path() + ".tmp" + if err := os.WriteFile(tmp, []byte(dir), 0o600); err != nil { + return err + } + return os.Rename(tmp, s.request_path()) +} diff --git a/kittens/file_manager/sync_test.go b/kittens/file_manager/sync_test.go new file mode 100644 index 0000000..0248aa7 --- /dev/null +++ b/kittens/file_manager/sync_test.go @@ -0,0 +1,100 @@ +// License: GPLv3 Copyright: 2026, FWS + +package file_manager + +import ( + "os" + "path/filepath" + "testing" +) + +func TestNewShellSyncNeedsOptionDirectoryAndWindow(t *testing.T) { + dir := t.TempDir() + if s := new_shell_sync(dir, "7", false); s != nil { + t.Fatal("the sync must stay off until the option is enabled") + } + if s := new_shell_sync("", "7", true); s != nil { + t.Fatal("the sync must be off without a session directory") + } + if s := new_shell_sync(dir, "", true); s != nil { + t.Fatal("the sync must be off without a shell window id") + } + if s := new_shell_sync(filepath.Join(dir, "missing"), "7", true); s != nil { + t.Fatal("the sync must be off when the session directory is missing") + } + if s := new_shell_sync(dir, "7", true); s == nil { + t.Fatal("the sync must be on with an option, a directory and a window id") + } +} + +func TestPublishRequestIsReadableAndLeavesNoTemporaryFile(t *testing.T) { + dir := t.TempDir() + s := new_shell_sync(dir, "42", true) + if err := s.publish_request("/tmp/target dir"); err != nil { + t.Fatal(err) + } + got, err := os.ReadFile(filepath.Join(dir, "42.set")) + if err != nil { + t.Fatal(err) + } + if string(got) != "/tmp/target dir" { + t.Fatalf("unexpected request payload %q", got) + } + if _, err = os.Stat(filepath.Join(dir, "42.set.tmp")); err == nil { + t.Fatal("the temporary file must be renamed, not left behind") + } +} + +func TestShellCwdIgnoresUnusablePaths(t *testing.T) { + dir := t.TempDir() + s := new_shell_sync(dir, "9", true) + published := filepath.Join(dir, "9") + for _, content := range []string{"", " \n", "relative/path", filepath.Join(dir, "gone")} { + if err := os.WriteFile(published, []byte(content), 0o600); err != nil { + t.Fatal(err) + } + if got := s.shell_cwd(); got != "" { + t.Fatalf("%q must not be followed, got %q", content, got) + } + } + if got := s.shell_cwd(); got != "" { + t.Fatalf("a missing file must not be followed, got %q", got) + } +} + +func TestNewTargetFollowsEachShellMoveOnce(t *testing.T) { + dir := t.TempDir() + s := new_shell_sync(dir, "3", true) + moved := t.TempDir() + s.last = dir + if got := s.new_target(dir); got != "" { + t.Fatalf("the shell has not moved yet, got %q", got) + } + if err := os.WriteFile(filepath.Join(dir, "3"), []byte(moved), 0o600); err != nil { + t.Fatal(err) + } + if got := s.new_target(dir); got != moved { + t.Fatalf("wanted %q, got %q", moved, got) + } + if got := s.new_target(dir); got != "" { + t.Fatalf("a shell move must only be followed once, got %q", got) + } + if err := os.WriteFile(filepath.Join(dir, "3"), []byte(dir), 0o600); err != nil { + t.Fatal(err) + } + if got := s.new_target(dir); got != "" { + t.Fatalf("moving to the directory already displayed must be a no-op, got %q", got) + } +} + +func TestResultPayloadAdvertisesSyncOnlyWhenHandled(t *testing.T) { + h := &Handler{result_action: "cd", result_path: "/tmp"} + if payload := h.result_payload(); len(payload) != 2 { + t.Fatalf("the shell must be typed into when the sync did not handle the move: %#v", payload) + } + h.sync_handled = true + payload := h.result_payload() + if payload["sync"] != "1" || payload["path"] != "/tmp" { + t.Fatalf("unexpected payload: %#v", payload) + } +} diff --git a/kitty/child.py b/kitty/child.py index da97631..b1b8c25 100644 --- a/kitty/child.py +++ b/kitty/child.py @@ -3,6 +3,7 @@ import os import sys +import tempfile import termios from collections import defaultdict from collections.abc import Callable, Generator, Iterable, Mapping, Sequence @@ -21,6 +22,20 @@ if TYPE_CHECKING: from .window import CwdRequest +@run_once +def cwd_sync_dir() -> str: + """Directory shared by every window of this instance for the file manager's + working directory sync. It is created with private permissions so that only + this user can read the paths the shells publish, and lives in the runtime + directory, which the login session already clears. An empty string means the + sync is unavailable and the participating kittens keep their own behaviour.""" + base = os.environ.get('XDG_RUNTIME_DIR') + try: + return tempfile.mkdtemp(prefix='kitty-cwd-sync-', dir=base if base and os.path.isdir(base) else None) + except OSError: + return '' + + if is_macos: from kitty.fast_data_types import abspath_of_process as _abspath_of_process from kitty.fast_data_types import cmdline_of_process as cmdline_ @@ -464,6 +479,7 @@ class Child: elif opts.terminfo_type == 'direct': env['TERMINFO'] = base64_terminfo_data() env['KITTY_INSTALLATION_DIR'] = kitty_base_dir + env['KITTY_CWD_SYNC_DIR'] = cwd_sync_dir() self.unmodified_argv = list(self.argv) if not self.should_run_via_run_shell_kitten and 'disabled' not in opts.shell_integration: from .shell_integration import modify_shell_environ diff --git a/kitty/tabs.py b/kitty/tabs.py index f1085da..bfade8b 100644 --- a/kitty/tabs.py +++ b/kitty/tabs.py @@ -927,6 +927,17 @@ class Tab: # {{{ restored_scrollback: bytes = b'', ) -> Window: "Create a new window. When dock is specified, the window is docked to dock_owner or to the tab if dock_owner is None." + # A special window opened over another one, or docked next to it, needs + # to know which shell it belongs to: the file manager uses it to find + # the session file where that shell publishes its working directory. A + # dock follows a window group, so its initial parent is the active + # window of the tab it is created in. + parent_window_id = overlay_for + if parent_window_id is None and dock is not None and (aw := self.active_window) is not None: + parent_window_id = aw.id + if parent_window_id is not None: + env = dict(env or {}) + env['KITTY_SPECIAL_WINDOW_PARENT'] = str(parent_window_id) cs = WindowCreationSpec( use_shell=use_shell, cmd=cmd, diff --git a/shell-integration/bash/kitty.bash b/shell-integration/bash/kitty.bash index 9b9d09e..f0c6af7 100644 --- a/shell-integration/bash/kitty.bash +++ b/shell-integration/bash/kitty.bash @@ -213,6 +213,10 @@ _ksi_main() { builtin printf "\e]7;kitty-shell-cwd://%s%s\a" "$HOSTNAME" "$PWD" fi fi + + if [[ -n "${_ksi_cwd_sync_file:-}" ]]; then + _ksi_cwd_sync_apply + fi } if [[ "${_ksi_prompt[cursor]}" == "y" ]]; then @@ -265,8 +269,34 @@ _ksi_main() { _ksi_prompt[ps2]+="\[\e]133;A;k=s\a\]" fi - builtin alias edit-in-kitty="kitten edit-in-kitty" + # Optional working directory sync with the file manager panel (sync_cwd). + # The panel publishes the directory it wants in /.set and we + # apply it at prompt time instead of typing a cd into the terminal: the + # command stays out of the history and a half typed multi-line command is + # not submitted. We publish our own directory the same way so that the panel + # can follow a cd made here. + if [[ -n "$KITTY_CWD_SYNC_DIR" && -n "$KITTY_WINDOW_ID" && -d "$KITTY_CWD_SYNC_DIR" ]]; then + _ksi_cwd_sync_file="$KITTY_CWD_SYNC_DIR/$KITTY_WINDOW_ID" + _ksi_cwd_sync_publish() { + builtin printf '%s' "$PWD" > "$_ksi_cwd_sync_file" 2> /dev/null + builtin return 0 + } + _ksi_cwd_sync_apply() { + builtin local ret=$? target + if [[ -f "$_ksi_cwd_sync_file.set" ]]; then + IFS= builtin read -r target < "$_ksi_cwd_sync_file.set" + builtin command rm -f -- "$_ksi_cwd_sync_file.set" + if [[ -n "$target" && -d "$target" ]]; then + builtin cd -- "$target" + fi + fi + _ksi_cwd_sync_publish + builtin return $ret + } + _ksi_cwd_sync_publish + fi + builtin alias edit-in-kitty="kitten edit-in-kitty" if [[ "${_ksi_prompt[complete]}" == "y" ]]; then _ksi_completions() { @@ -315,6 +345,7 @@ _ksi_main() { # from the shell builtin local pc pc='builtin declare -F _ksi_prompt_command > /dev/null 2> /dev/null && _ksi_prompt_command' + if [[ -n "${_ksi_cwd_sync_file:-}" ]]; then pc="$pc; _ksi_cwd_sync_apply"; fi if [[ -z "${PROMPT_COMMAND[*]}" ]]; then PROMPT_COMMAND=([0]="$pc") elif [[ $(builtin declare -p PROMPT_COMMAND 2> /dev/null) =~ 'declare -a PROMPT_COMMAND' ]]; then diff --git a/shell-integration/fish/vendor_conf.d/kitty-shell-integration.fish b/shell-integration/fish/vendor_conf.d/kitty-shell-integration.fish index ced297e..49af66f 100644 --- a/shell-integration/fish/vendor_conf.d/kitty-shell-integration.fish +++ b/shell-integration/fish/vendor_conf.d/kitty-shell-integration.fish @@ -137,6 +137,28 @@ function __ksi_schedule --on-event fish_prompt -d "Setup kitty integration after __update_cwd_osc end + # Optional working directory sync with the file manager panel (sync_cwd). + # The panel publishes the directory it wants in /.set and we + # apply it at prompt time instead of typing a cd into the terminal, see the + # bash integration for the rationale. + if set -q KITTY_CWD_SYNC_DIR; and set -q KITTY_WINDOW_ID; and test -d "$KITTY_CWD_SYNC_DIR" + function __ksi_cwd_sync_publish --on-event fish_prompt -d "Publish the working directory for the file manager panel" + printf '%s' "$PWD" > "$KITTY_CWD_SYNC_DIR/$KITTY_WINDOW_ID" 2> /dev/null + end + function __ksi_cwd_sync_apply --on-event fish_prompt -d "Apply a directory chosen in the file manager panel" + set --local file "$KITTY_CWD_SYNC_DIR/$KITTY_WINDOW_ID.set" + if test -f "$file" + set --local target (cat "$file") + rm -f -- "$file" + if test -n "$target" -a -d "$target" + builtin cd -- "$target" + end + end + __ksi_cwd_sync_publish + end + __ksi_cwd_sync_publish + end + # Note that neither alias nor function is recursive in fish so if the user defines an alias/function # for sudo/run0 it will be clobbered by us, so only install these if they are not already functions if not contains "no-sudo" $_ksi diff --git a/shell-integration/zsh/kitty-integration b/shell-integration/zsh/kitty-integration index 40ef8bf..642a44b 100644 --- a/shell-integration/zsh/kitty-integration +++ b/shell-integration/zsh/kitty-integration @@ -246,6 +246,31 @@ _ksi_deferred_init() { _ksi_report_pwd fi + # Optional working directory sync with the file manager panel (sync_cwd). + # The panel publishes the directory it wants in /.set and we + # apply it at prompt time instead of typing a cd into the terminal, see the + # bash integration for the rationale. + if [[ -n $KITTY_CWD_SYNC_DIR && -n $KITTY_WINDOW_ID && -d $KITTY_CWD_SYNC_DIR ]]; then + builtin typeset -g _ksi_cwd_sync_file="$KITTY_CWD_SYNC_DIR/$KITTY_WINDOW_ID" + _ksi_cwd_sync_publish() { builtin print -rn -- "$PWD" >| "$_ksi_cwd_sync_file" 2> /dev/null; } + _ksi_cwd_sync_apply() { + builtin local -i ret=$? + builtin local target + if [[ -f "$_ksi_cwd_sync_file.set" ]]; then + IFS= builtin read -r target < "$_ksi_cwd_sync_file.set" + builtin command rm -f -- "$_ksi_cwd_sync_file.set" + if [[ -n $target && -d $target ]]; then + builtin cd -- "$target" + fi + fi + _ksi_cwd_sync_publish + builtin return ret + } + _ksi_cwd_sync_publish + precmd_functions+=(_ksi_cwd_sync_apply) + chpwd_functions+=(_ksi_cwd_sync_publish) + fi + # Enable terminal title changes. if (( ! opt[(Ie)no-title] )); then # We don't use `print -P` because it depends on prompt options, which From e7e4e849eb0c952d11680cdf12f95faea31ea420 Mon Sep 17 00:00:00 2001 From: BlackAngelTVdev Date: Wed, 11 Nov 2026 08:35:19 +0100 Subject: [PATCH 2/3] feat(file-manager): sync the working directory by default The panel and the shell now share their directory out of the box; whoever wants the previous independence sets sync_cwd no. The request is only written once the shell has published its directory, since that file is what proves its integration hook will read the request: a shell without shell integration still gets the cd typed into the terminal instead of losing the change. --- docs/changelog.rst | 13 +++++++------ docs/kittens/file-manager.rst | 13 ++++++------- kittens/file_manager/main.go | 5 ++++- kittens/file_manager/main.py | 5 +++-- kittens/file_manager/main_test.go | 13 +++++++++++++ kittens/file_manager/sync.go | 8 ++++++++ kittens/file_manager/sync_test.go | 20 ++++++++++++++++++++ 7 files changed, 61 insertions(+), 16 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index 792a045..ce2c664 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -222,12 +222,13 @@ Detailed list of changes 0.50.1 [unreleased] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- The :doc:`file manager ` can now keep its directory in - step with the shell: with :code:`sync_cwd yes`, a :code:`cd` moves the panel - into the same directory and validating a directory moves the shell at its - next prompt, for bash, zsh and fish. Nothing is typed into the terminal, so - no command lands in the history and a multi-line command being typed is left - untouched. +- The :doc:`file manager ` now keeps its directory in + step with the shell by default: a :code:`cd` moves the panel into the same + directory and validating a directory moves the shell at its next prompt, for + bash, zsh and fish. Nothing is typed into the terminal, so no command lands + in the history and a multi-line command being typed is left untouched. Set + :code:`sync_cwd no` in :file:`file-manager.conf` to keep the two directories + independent, as before. - :kbd:`Ctrl+Shift+E` now opens the :doc:`file manager kitten ` in a left dock by default, instead of requiring a diff --git a/docs/kittens/file-manager.rst b/docs/kittens/file-manager.rst index efb6f95..447ad46 100644 --- a/docs/kittens/file-manager.rst +++ b/docs/kittens/file-manager.rst @@ -98,15 +98,14 @@ Actions Synchronisation avec le shell ------------------------------ -Par défaut, le panneau et le shell gardent chacun leur répertoire : le panneau -part de celui du shell, mais un :code:`cd` d'un côté ne change rien de l'autre. -L'option ``sync_cwd`` les tient synchronisés dans les deux sens :: +Le panneau et le shell partagent leur répertoire courant depuis la version +0.50.1 : un :code:`cd` dans le shell amène le panneau dans le même répertoire, +et valider un répertoire dans le panneau amène le shell vers celui-ci. Pour que +chacun garde son propre répertoire, alors que le panneau part toujours de celui +du shell et n'en change plus :: # ~/.config/kitty/file-manager.conf - sync_cwd yes - -Un :code:`cd` dans le shell amène alors le panneau dans le même répertoire, et -valider un répertoire dans le panneau amène le shell vers celui-ci. + sync_cwd no L'échange ne passe pas par le terminal. kitty exporte un répertoire de session dans :envvar:`KITTY_CWD_SYNC_DIR` ; le shell y publie son répertoire courant et diff --git a/kittens/file_manager/main.go b/kittens/file_manager/main.go index 645bc11..a3424d9 100644 --- a/kittens/file_manager/main.go +++ b/kittens/file_manager/main.go @@ -495,7 +495,10 @@ func (h *Handler) change_shell_dir_to(path string) { h.result_action, h.result_path = "cd", path // With the sync on, the shell reads the request from its session file at the // next prompt, so the handler must not also type the change into its pty. - if h.sync != nil && h.sync.publish_request(path) == nil { + // The request is only written once the shell proved it has the hook by + // publishing its directory: a shell without shell integration would + // otherwise never see it and the change would be silently lost. + if h.sync != nil && h.sync.shell_has_hook() && h.sync.publish_request(path) == nil { h.sync_handled = true } h.lp.Quit(0) diff --git a/kittens/file_manager/main.py b/kittens/file_manager/main.py index 9d34c21..d878c89 100644 --- a/kittens/file_manager/main.py +++ b/kittens/file_manager/main.py @@ -51,7 +51,7 @@ agr('shell', 'Shell synchronisation') opt( 'sync_cwd', - 'no', + 'yes', option_type='to_bool', long_text=""" Keep the shell's working directory and the panel in step. A :code:`cd` in the @@ -62,7 +62,8 @@ The exchange goes through two small files in the session directory kitty exports as :envvar:`KITTY_CWD_SYNC_DIR`, so nothing is typed into the shell: the command never lands in the history and a half typed multi-line command is left untouched. Bash, zsh and fish are supported by their kitty shell -integration; other shells keep the current behaviour. +integration; other shells keep the current behaviour. Set :code:`sync_cwd no` +to keep the two directories independent. """, ) diff --git a/kittens/file_manager/main_test.go b/kittens/file_manager/main_test.go index 37fc29b..9210642 100644 --- a/kittens/file_manager/main_test.go +++ b/kittens/file_manager/main_test.go @@ -180,6 +180,19 @@ func TestOpenWithSudoOption(t *testing.T) { } } +func TestSyncCwdIsOnByDefault(t *testing.T) { + c := NewConfig() + if !c.Sync_cwd { + t.Fatal("the panel must follow the shell by default") + } + if err := c.Parse("sync_cwd", "no"); err != nil { + t.Fatal(err) + } + if c.Sync_cwd { + t.Fatal("sync_cwd = no must keep the two directories independent") + } +} + func TestEditArgs(t *testing.T) { got := edit_args("/tmp/a.py") want := []string{"edit-in-kitty", "--type=tab", "/tmp/a.py"} diff --git a/kittens/file_manager/sync.go b/kittens/file_manager/sync.go index 5361687..bc4b77b 100644 --- a/kittens/file_manager/sync.go +++ b/kittens/file_manager/sync.go @@ -42,6 +42,14 @@ func new_shell_sync_from_env(enabled bool) *shell_sync { func (s *shell_sync) shell_cwd_path() string { return filepath.Join(s.dir, s.window_id) } func (s *shell_sync) request_path() string { return s.shell_cwd_path() + ".set" } +// shell_has_hook reports whether the shell has published its working directory +// at least once, which only the integration hook does. Without it nothing would +// consume the request, so the panel has to type the change into the shell. +func (s *shell_sync) shell_has_hook() bool { + _, err := os.Stat(s.shell_cwd_path()) + return err == nil +} + // shell_cwd returns the working directory last published by the shell. An empty // or relative path, or one that no longer exists, is treated as unknown rather // than followed, as the shell may be between two writes. diff --git a/kittens/file_manager/sync_test.go b/kittens/file_manager/sync_test.go index 0248aa7..3a10340 100644 --- a/kittens/file_manager/sync_test.go +++ b/kittens/file_manager/sync_test.go @@ -45,6 +45,26 @@ func TestPublishRequestIsReadableAndLeavesNoTemporaryFile(t *testing.T) { } } +func TestShellHasHookNeedsAPublishedDirectory(t *testing.T) { + dir := t.TempDir() + s := new_shell_sync(dir, "5", true) + if s.shell_has_hook() { + t.Fatal("the shell published nothing yet") + } + if err := s.publish_request(dir); err != nil { + t.Fatal(err) + } + if s.shell_has_hook() { + t.Fatal("a request must not be mistaken for a published directory") + } + if err := os.WriteFile(filepath.Join(dir, "5"), []byte(dir), 0o600); err != nil { + t.Fatal(err) + } + if !s.shell_has_hook() { + t.Fatal("a published directory means the shell has the hook") + } +} + func TestShellCwdIgnoresUnusablePaths(t *testing.T) { dir := t.TempDir() s := new_shell_sync(dir, "9", true) From 5d2e28b1441e3a95917b99b29c0543cc70845cd9 Mon Sep 17 00:00:00 2001 From: BlackAngelTVdev Date: Wed, 11 Nov 2026 08:48:03 +0100 Subject: [PATCH 3/3] feat(file-manager): move the shell while browsing the panel Opening a directory in the panel now hands it to the shell, so walking the tree reads like cd and the two stay on the same directory. The request is still read at the shell's next prompt, and quitting without validating withdraws a request the shell has not read yet, so Esc keeps leaving the shell where it was. --- docs/changelog.rst | 10 +++++----- docs/kittens/file-manager.rst | 22 ++++++++++++--------- kittens/file_manager/main.go | 33 +++++++++++++++++++++++++++++-- kittens/file_manager/main.py | 5 +++-- kittens/file_manager/sync.go | 6 ++++++ kittens/file_manager/sync_test.go | 30 ++++++++++++++++++++++++++++ 6 files changed, 88 insertions(+), 18 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index ce2c664..1b843ca 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -224,11 +224,11 @@ Detailed list of changes - The :doc:`file manager ` now keeps its directory in step with the shell by default: a :code:`cd` moves the panel into the same - directory and validating a directory moves the shell at its next prompt, for - bash, zsh and fish. Nothing is typed into the terminal, so no command lands - in the history and a multi-line command being typed is left untouched. Set - :code:`sync_cwd no` in :file:`file-manager.conf` to keep the two directories - independent, as before. + directory and walking through the panel moves the shell at its next prompt, + for bash, zsh and fish. Nothing is typed into the terminal, so no command + lands in the history and a multi-line command being typed is left untouched. + Set :code:`sync_cwd no` in :file:`file-manager.conf` to keep the two + directories independent, as before. - :kbd:`Ctrl+Shift+E` now opens the :doc:`file manager kitten ` in a left dock by default, instead of requiring a diff --git a/docs/kittens/file-manager.rst b/docs/kittens/file-manager.rst index 447ad46..8f87b8c 100644 --- a/docs/kittens/file-manager.rst +++ b/docs/kittens/file-manager.rst @@ -59,7 +59,8 @@ Actions utilisez :code:`sudo -e` depuis le shell. :kbd:`→` ou :kbd:`L` - descend dans le répertoire sélectionné sans toucher au shell. + descend dans le répertoire sélectionné ; le shell y va aussi, au prompt + suivant, quand la synchronisation est active. :kbd:`←`, :kbd:`Retour arrière` ou :kbd:`H` remonte au répertoire parent. @@ -92,17 +93,19 @@ Actions affiche ou masque les entrées cachées. :kbd:`Échap` ou :kbd:`Q` - ferme le panneau sans rien changer. + ferme le panneau sans rien changer : une demande de synchronisation que le + shell n'a pas encore lue est retirée, il reste donc où il était. Synchronisation avec le shell ------------------------------ Le panneau et le shell partagent leur répertoire courant depuis la version -0.50.1 : un :code:`cd` dans le shell amène le panneau dans le même répertoire, -et valider un répertoire dans le panneau amène le shell vers celui-ci. Pour que -chacun garde son propre répertoire, alors que le panneau part toujours de celui -du shell et n'en change plus :: +0.50.1, dans les deux sens : un :code:`cd` dans le shell amène le panneau dans +le même répertoire, et chaque répertoire ouvert dans le panneau devient aussi +celui du shell, sans même avoir à valider. Pour que chacun garde son propre +répertoire, alors que le panneau part toujours de celui du shell et n'en change +plus :: # ~/.config/kitty/file-manager.conf sync_cwd no @@ -123,9 +126,10 @@ pas soumise. l'option est désactivée. Le changement est appliqué au prompt suivant : le shell se déplace quand la - commande suivante démarre, ou qu'une ligne vide est validée, et non à - l'instant où le panneau se ferme. C'est le prix à payer pour ne jamais écrire - dans le terminal. + commande suivante démarre, ou qu'une ligne vide est validée, et non pendant + que vous parcourez le panneau. C'est le prix à payer pour ne jamais écrire + dans le terminal. Si vous quittez le panneau avec :kbd:`Échap` avant que le + shell ait lu la demande, elle est retirée et le shell ne bouge pas. Lancé dans un dock, le panneau suit la fenêtre active du groupe au moment où le dock est créé. Si vous passez ensuite à une autre fenêtre du même groupe, diff --git a/kittens/file_manager/main.go b/kittens/file_manager/main.go index a3424d9..cc1e194 100644 --- a/kittens/file_manager/main.go +++ b/kittens/file_manager/main.go @@ -206,6 +206,7 @@ type Handler struct { keyboard_shortcuts []*config.KeyAction sync *shell_sync sync_handled bool + sync_published bool } func (h *Handler) initialize() (string, error) { @@ -236,6 +237,32 @@ func (h *Handler) initialize() (string, error) { return "", nil } +// publish_browse hands the directory the user just opened in the panel to the +// shell, so that walking through the tree in the panel walks the shell through +// it too. The shell reads the request at its next prompt; until then the panel +// remembers it so that quitting can withdraw it. +func (h *Handler) publish_browse() { + if h.sync == nil || !h.sync.shell_has_hook() { + return + } + if err := h.sync.publish_request(h.cwd); err != nil { + return + } + h.sync_published = true +} + +// withdraw_sync_request drops a request published by browsing, so that leaving +// the panel without validating a directory leaves the shell where it was. It +// does nothing once the shell has read the request, which it only does at a +// prompt. +func (h *Handler) withdraw_sync_request() { + if !h.sync_published { + return + } + h.sync.withdraw_request() + h.sync_published = false +} + // follow_shell_cwd mirrors a cd made in the shell into the panel, keeping the // selection on the same name so that the cursor does not jump around. func (h *Handler) follow_shell_cwd() { @@ -318,6 +345,7 @@ func (h *Handler) change_dir(dir string) { } h.selected, h.scroll, h.message = 0, 0, "" h.draw_screen() + h.publish_browse() } func (h *Handler) move_selection(delta int) { @@ -480,8 +508,8 @@ func (h *Handler) open_file(path string) { h.draw_screen() } -// enter_dir browses into the selected directory inside the panel, leaving the -// working directory of the shell untouched. +// enter_dir browses into the selected directory inside the panel and hands it to +// the shell, so that both stay on the same directory. func (h *Handler) enter_dir() { e, ok := h.selected_entry() if !ok || !e.IsDir { @@ -518,6 +546,7 @@ func (h *Handler) change_shell_dir() { func (h *Handler) perform_action(name string) { switch name { case "quit": + h.withdraw_sync_request() h.lp.Quit(0) case "move_up": h.move_selection(-1) diff --git a/kittens/file_manager/main.py b/kittens/file_manager/main.py index d878c89..c2e031b 100644 --- a/kittens/file_manager/main.py +++ b/kittens/file_manager/main.py @@ -55,8 +55,9 @@ opt( option_type='to_bool', long_text=""" Keep the shell's working directory and the panel in step. A :code:`cd` in the -shell moves the panel to the same directory, and validating a directory in the -panel makes the shell change to it at its next prompt. +shell moves the panel to the same directory, and walking through the panel moves +the shell to the directory being browsed at its next prompt. Quitting the panel +without validating a directory withdraws a request the shell has not read yet. The exchange goes through two small files in the session directory kitty exports as :envvar:`KITTY_CWD_SYNC_DIR`, so nothing is typed into the shell: diff --git a/kittens/file_manager/sync.go b/kittens/file_manager/sync.go index bc4b77b..16de11b 100644 --- a/kittens/file_manager/sync.go +++ b/kittens/file_manager/sync.go @@ -91,3 +91,9 @@ func (s *shell_sync) publish_request(dir string) error { } return os.Rename(tmp, s.request_path()) } + +// withdraw_request cancels a request the shell has not read yet. Removing a +// request it already consumed is not an error, the shell removes it itself. +func (s *shell_sync) withdraw_request() { + _ = os.Remove(s.request_path()) +} diff --git a/kittens/file_manager/sync_test.go b/kittens/file_manager/sync_test.go index 3a10340..36394e0 100644 --- a/kittens/file_manager/sync_test.go +++ b/kittens/file_manager/sync_test.go @@ -65,6 +65,36 @@ func TestShellHasHookNeedsAPublishedDirectory(t *testing.T) { } } +func TestPublishBrowseNeedsTheShellHookAndCanBeWithdrawn(t *testing.T) { + dir := t.TempDir() + h := &Handler{sync: new_shell_sync(dir, "11", true), cwd: dir} + h.publish_browse() + if _, err := os.Stat(filepath.Join(dir, "11.set")); err == nil { + t.Fatal("the panel must not publish before the shell proved it has the hook") + } + if h.sync_published { + t.Fatal("nothing was published") + } + if err := os.WriteFile(filepath.Join(dir, "11"), []byte(dir), 0o600); err != nil { + t.Fatal(err) + } + h.publish_browse() + if got, err := os.ReadFile(filepath.Join(dir, "11.set")); err != nil || string(got) != dir { + t.Fatalf("unexpected request %q (%v)", got, err) + } + if !h.sync_published { + t.Fatal("the request must be remembered so that quitting can withdraw it") + } + h.withdraw_sync_request() + if _, err := os.Stat(filepath.Join(dir, "11.set")); err == nil { + t.Fatal("quitting must withdraw the pending request") + } + if h.sync_published { + t.Fatal("nothing is pending anymore") + } + h.withdraw_sync_request() +} + func TestShellCwdIgnoresUnusablePaths(t *testing.T) { dir := t.TempDir() s := new_shell_sync(dir, "9", true)