diff --git a/docs/changelog.rst b/docs/changelog.rst index bb8a586..51f8070 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -244,6 +244,14 @@ Detailed list of changes automatic, and a corrupt or oversized saved state is discarded instead of blocking startup. See :ref:`sessions` for details. +- 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 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 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 3d7ff34..716f9a8 100644 --- a/docs/kittens/file-manager.rst +++ b/docs/kittens/file-manager.rst @@ -35,7 +35,8 @@ est passé en argument ou avec ``--start-dir``. panneau a été lancé. Lancé dans un dock ou un panneau du bureau, il ne change donc pas le répertoire du shell : :kbd:`Ctrl+Entrée` ferme le panneau sans déplacer le shell. Lancez le panneau depuis une fenêtre de shell pour changer - de répertoire. + de répertoire, 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 @@ -59,7 +60,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. @@ -111,7 +113,49 @@ 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, dans les deux sens : un :code:`cd` dans le shell amène le panneau dans +le même répertoire, et chaque répertoire ouvert dans le panneau devient aussi +celui du shell, sans même avoir à valider. Pour que chacun garde son propre +répertoire, alors que le panneau part toujours de celui du shell et n'en change +plus :: + + # ~/.config/kitty/file-manager.conf + sync_cwd no + +L'échange ne passe pas par le terminal. kitty exporte un répertoire de session +dans :envvar:`KITTY_CWD_SYNC_DIR` ; le shell y publie son répertoire courant et +le panneau y dépose celui qu'il veut. Le panneau retrouve le shell qui l'a lancé +grâce à :envvar:`KITTY_SPECIAL_WINDOW_PARENT`. L'intégration shell de kitty, pour +bash, zsh et fish, applique la demande avec :code:`builtin cd` : aucune commande +n'entre dans l'historique et une commande multi-lignes en cours de saisie n'est +pas soumise. + +.. note:: + + La synchronisation demande l'intégration shell de kitty, active par défaut + pour bash, zsh et fish. Les autres shells gardent le comportement précédent : + le panneau retape la commande :code:`cd` dans le terminal, comme lorsque + l'option est désactivée. + + Le changement est appliqué au prompt suivant : le shell se déplace quand la + commande suivante démarre, ou qu'une ligne vide est validée, et non pendant + que vous parcourez le panneau. C'est le prix à payer pour ne jamais écrire + dans le terminal. Si vous quittez le panneau avec :kbd:`Échap` avant que le + shell ait lu la demande, elle est retirée et le shell ne bouge pas. + + Lancé dans un dock, le panneau suit la fenêtre active du groupe au moment où + le dock est créé. Si vous passez ensuite à une autre fenêtre du même groupe, + il continue de suivre cette première fenêtre : relancez le dock pour changer + de cible. Dans un panneau du bureau, il n'y a pas de shell à suivre et la + synchronisation reste inerte. .. _file-manager-shortcuts: diff --git a/kittens/file_manager/main.go b/kittens/file_manager/main.go index b9a05fa..547899d 100644 --- a/kittens/file_manager/main.go +++ b/kittens/file_manager/main.go @@ -221,6 +221,9 @@ type Handler struct { result_path string shortcut_tracker config.ShortcutTracker keyboard_shortcuts []*config.KeyAction + sync *shell_sync + sync_handled bool + sync_published bool } func (h *Handler) initialize() (string, error) { @@ -235,11 +238,69 @@ 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 } +// publish_browse hands the directory the user just opened in the panel to the +// shell, so that walking through the tree in the panel walks the shell through +// it too. The shell reads the request at its next prompt; until then the panel +// remembers it so that quitting can withdraw it. +func (h *Handler) publish_browse() { + if h.sync == nil || !h.sync.shell_has_hook() { + return + } + if err := h.sync.publish_request(h.cwd); err != nil { + return + } + h.sync_published = true +} + +// withdraw_sync_request drops a request published by browsing, so that leaving +// the panel without validating a directory leaves the shell where it was. It +// does nothing once the shell has read the request, which it only does at a +// prompt. +func (h *Handler) withdraw_sync_request() { + if !h.sync_published { + return + } + h.sync.withdraw_request() + h.sync_published = false +} + +// follow_shell_cwd mirrors a cd made in the shell into the panel, keeping the +// selection on the same name so that the cursor does not jump around. +func (h *Handler) follow_shell_cwd() { + if h.sync == nil { + return + } + dir := h.sync.new_target(h.cwd) + if dir == "" { + return + } + name := "" + if e, ok := h.selected_entry(); ok { + name = e.Name + } + if err := h.load(dir); err != nil { + return + } + h.select_name(name) + h.draw_screen() +} + // load reads dir and adopts it as the current directory. Selection is clamped // rather than reset so that reloading a directory after an action keeps the // cursor near where it was. @@ -309,6 +370,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) { @@ -483,8 +545,8 @@ func (h *Handler) open_file_in(path, window_type 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 { @@ -496,6 +558,14 @@ 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. + // 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) } @@ -546,7 +616,10 @@ var action_catalog = []action_info{ // 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) }, + "quit": func(h *Handler) { + h.withdraw_sync_request() + 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) { @@ -1136,7 +1209,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) { @@ -1165,7 +1242,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 2bb3376..5770305 100644 --- a/kittens/file_manager/main.py +++ b/kittens/file_manager/main.py @@ -48,6 +48,29 @@ directories first, then files sorted by size, largest first. egr() +agr('shell', 'Shell synchronisation') + +opt( + 'sync_cwd', + 'yes', + option_type='to_bool', + long_text=""" +Keep the shell's working directory and the panel in step. A :code:`cd` in the +shell moves the panel to the same directory, and walking through the panel moves +the shell to the directory being browsed at its next prompt. Quitting the panel +without validating a directory withdraws a request the shell has not read yet. + +The exchange goes through two small files in the session directory kitty +exports as :envvar:`KITTY_CWD_SYNC_DIR`, so nothing is typed into the shell: +the command never lands in the history and a half typed multi-line command is +left untouched. Bash, zsh and fish are supported by their kitty shell +integration; other shells keep the current behaviour. Set :code:`sync_cwd no` +to keep the two directories independent. +""", +) + +egr() + agr('opening', 'Opening files') opt( @@ -219,6 +242,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/main_test.go b/kittens/file_manager/main_test.go index 752fae7..7c1f93b 100644 --- a/kittens/file_manager/main_test.go +++ b/kittens/file_manager/main_test.go @@ -182,6 +182,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 new file mode 100644 index 0000000..16de11b --- /dev/null +++ b/kittens/file_manager/sync.go @@ -0,0 +1,99 @@ +// 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_has_hook reports whether the shell has published its working directory +// at least once, which only the integration hook does. Without it nothing would +// consume the request, so the panel has to type the change into the shell. +func (s *shell_sync) shell_has_hook() bool { + _, err := os.Stat(s.shell_cwd_path()) + return err == nil +} + +// shell_cwd returns the working directory last published by the shell. An empty +// or relative path, or one that no longer exists, is treated as unknown rather +// than followed, as the shell may be between two writes. +func (s *shell_sync) shell_cwd() string { + b, err := os.ReadFile(s.shell_cwd_path()) + if err != nil { + return "" + } + p := strings.TrimSpace(string(b)) + if !filepath.IsAbs(p) { + return "" + } + if info, err := os.Stat(p); err != nil || !info.IsDir() { + return "" + } + return p +} + +// new_target returns the directory the panel should move to, or "" when the +// shell has not moved since the last call or already sits in current. +func (s *shell_sync) new_target(current string) string { + p := s.shell_cwd() + if p == "" || p == s.last { + return "" + } + s.last = p + if p == current { + return "" + } + return p +} + +// publish_request hands a directory to the shell. The write goes through a +// temporary file so that the shell never reads a half written path. +func (s *shell_sync) publish_request(dir string) error { + tmp := s.request_path() + ".tmp" + if err := os.WriteFile(tmp, []byte(dir), 0o600); err != nil { + return err + } + return os.Rename(tmp, s.request_path()) +} + +// withdraw_request cancels a request the shell has not read yet. Removing a +// request it already consumed is not an error, the shell removes it itself. +func (s *shell_sync) withdraw_request() { + _ = os.Remove(s.request_path()) +} diff --git a/kittens/file_manager/sync_test.go b/kittens/file_manager/sync_test.go new file mode 100644 index 0000000..36394e0 --- /dev/null +++ b/kittens/file_manager/sync_test.go @@ -0,0 +1,150 @@ +// License: GPLv3 Copyright: 2026, FWS + +package file_manager + +import ( + "os" + "path/filepath" + "testing" +) + +func TestNewShellSyncNeedsOptionDirectoryAndWindow(t *testing.T) { + dir := t.TempDir() + if s := new_shell_sync(dir, "7", false); s != nil { + t.Fatal("the sync must stay off until the option is enabled") + } + if s := new_shell_sync("", "7", true); s != nil { + t.Fatal("the sync must be off without a session directory") + } + if s := new_shell_sync(dir, "", true); s != nil { + t.Fatal("the sync must be off without a shell window id") + } + if s := new_shell_sync(filepath.Join(dir, "missing"), "7", true); s != nil { + t.Fatal("the sync must be off when the session directory is missing") + } + if s := new_shell_sync(dir, "7", true); s == nil { + t.Fatal("the sync must be on with an option, a directory and a window id") + } +} + +func TestPublishRequestIsReadableAndLeavesNoTemporaryFile(t *testing.T) { + dir := t.TempDir() + s := new_shell_sync(dir, "42", true) + if err := s.publish_request("/tmp/target dir"); err != nil { + t.Fatal(err) + } + got, err := os.ReadFile(filepath.Join(dir, "42.set")) + if err != nil { + t.Fatal(err) + } + if string(got) != "/tmp/target dir" { + t.Fatalf("unexpected request payload %q", got) + } + if _, err = os.Stat(filepath.Join(dir, "42.set.tmp")); err == nil { + t.Fatal("the temporary file must be renamed, not left behind") + } +} + +func TestShellHasHookNeedsAPublishedDirectory(t *testing.T) { + dir := t.TempDir() + s := new_shell_sync(dir, "5", true) + if s.shell_has_hook() { + t.Fatal("the shell published nothing yet") + } + if err := s.publish_request(dir); err != nil { + t.Fatal(err) + } + if s.shell_has_hook() { + t.Fatal("a request must not be mistaken for a published directory") + } + if err := os.WriteFile(filepath.Join(dir, "5"), []byte(dir), 0o600); err != nil { + t.Fatal(err) + } + if !s.shell_has_hook() { + t.Fatal("a published directory means the shell has the hook") + } +} + +func TestPublishBrowseNeedsTheShellHookAndCanBeWithdrawn(t *testing.T) { + dir := t.TempDir() + h := &Handler{sync: new_shell_sync(dir, "11", true), cwd: dir} + h.publish_browse() + if _, err := os.Stat(filepath.Join(dir, "11.set")); err == nil { + t.Fatal("the panel must not publish before the shell proved it has the hook") + } + if h.sync_published { + t.Fatal("nothing was published") + } + if err := os.WriteFile(filepath.Join(dir, "11"), []byte(dir), 0o600); err != nil { + t.Fatal(err) + } + h.publish_browse() + if got, err := os.ReadFile(filepath.Join(dir, "11.set")); err != nil || string(got) != dir { + t.Fatalf("unexpected request %q (%v)", got, err) + } + if !h.sync_published { + t.Fatal("the request must be remembered so that quitting can withdraw it") + } + h.withdraw_sync_request() + if _, err := os.Stat(filepath.Join(dir, "11.set")); err == nil { + t.Fatal("quitting must withdraw the pending request") + } + if h.sync_published { + t.Fatal("nothing is pending anymore") + } + h.withdraw_sync_request() +} + +func TestShellCwdIgnoresUnusablePaths(t *testing.T) { + dir := t.TempDir() + s := new_shell_sync(dir, "9", true) + published := filepath.Join(dir, "9") + for _, content := range []string{"", " \n", "relative/path", filepath.Join(dir, "gone")} { + if err := os.WriteFile(published, []byte(content), 0o600); err != nil { + t.Fatal(err) + } + if got := s.shell_cwd(); got != "" { + t.Fatalf("%q must not be followed, got %q", content, got) + } + } + if got := s.shell_cwd(); got != "" { + t.Fatalf("a missing file must not be followed, got %q", got) + } +} + +func TestNewTargetFollowsEachShellMoveOnce(t *testing.T) { + dir := t.TempDir() + s := new_shell_sync(dir, "3", true) + moved := t.TempDir() + s.last = dir + if got := s.new_target(dir); got != "" { + t.Fatalf("the shell has not moved yet, got %q", got) + } + if err := os.WriteFile(filepath.Join(dir, "3"), []byte(moved), 0o600); err != nil { + t.Fatal(err) + } + if got := s.new_target(dir); got != moved { + t.Fatalf("wanted %q, got %q", moved, got) + } + if got := s.new_target(dir); got != "" { + t.Fatalf("a shell move must only be followed once, got %q", got) + } + if err := os.WriteFile(filepath.Join(dir, "3"), []byte(dir), 0o600); err != nil { + t.Fatal(err) + } + if got := s.new_target(dir); got != "" { + t.Fatalf("moving to the directory already displayed must be a no-op, got %q", got) + } +} + +func TestResultPayloadAdvertisesSyncOnlyWhenHandled(t *testing.T) { + h := &Handler{result_action: "cd", result_path: "/tmp"} + if payload := h.result_payload(); len(payload) != 2 { + t.Fatalf("the shell must be typed into when the sync did not handle the move: %#v", payload) + } + h.sync_handled = true + payload := h.result_payload() + if payload["sync"] != "1" || payload["path"] != "/tmp" { + t.Fatalf("unexpected payload: %#v", payload) + } +} 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 a2d89d6..1cb53ae 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