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.
This commit is contained in:
BlackAngelTV committed 2026-11-11 08:20:11 +01:00
1 parent f16ed6cbfe
commit 1b330bcf81
12 files changed
+425 -6

No files matched your search

+7
View File
@@ -222,6 +222,13 @@ Detailed list of changes
0.50.1 [unreleased]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
- The :doc:`file manager <kittens/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
<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
+14 -1
View File
@@ -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 <window>` kitty dans
laquelle le programme s'exécute. Utilisable avec la :doc:`facilité de
contrôle à distance de kitty <remote-control>`.
.. envvar:: KITTY_CWD_SYNC_DIR
Le répertoire de session dans lequel les shells et les kittens qui coopèrent
échangent leur répertoire courant, voir la :ref:`synchronisation du
gestionnaire de fichiers <file_manager>`. Il n'est lisible que par votre
utilisateur et disparaît à la fin de la session.
.. envvar:: KITTY_SPECIAL_WINDOW_PARENT
Un entier qui est l'identifiant de la :term:`fenêtre <window>` pour laquelle
une fenêtre spéciale (overlay ou dock) a été ouverte. Absent des fenêtres
normales ; le :doc:`gestionnaire de fichiers </kittens/file-manager>` s'en
sert pour retrouver le shell dont il suit le répertoire.
.. envvar:: KITTY_PID
Un entier qui est l'identifiant du processus kitty dans lequel le programme
+43 -2
View File
@@ -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
+45 -2
View File
@@ -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)
+25
View File
@@ -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()
+85
View File
@@ -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 <dir>/<window id>, the panel publishes the directory it wants in
// <dir>/<window id>.set. The shell applies that request from its prompt hook,
// which keeps the command out of the history and leaves a half typed multi-line
// command alone.
type shell_sync struct {
dir string
window_id string
last string
}
func new_shell_sync(dir, window_id string, enabled bool) *shell_sync {
if !enabled || dir == "" || window_id == "" {
return nil
}
if info, err := os.Stat(dir); err != nil || !info.IsDir() {
return nil
}
return &shell_sync{dir: dir, window_id: window_id}
}
// new_shell_sync_from_env is nil whenever the option is off or kitty did not
// give the panel a shell window to talk to, in which case the panel keeps its
// own behaviour and types the change into the shell instead.
func new_shell_sync_from_env(enabled bool) *shell_sync {
return new_shell_sync(os.Getenv("KITTY_CWD_SYNC_DIR"), os.Getenv("KITTY_SPECIAL_WINDOW_PARENT"), enabled)
}
func (s *shell_sync) shell_cwd_path() string { return filepath.Join(s.dir, s.window_id) }
func (s *shell_sync) request_path() string { return s.shell_cwd_path() + ".set" }
// shell_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())
}
+100
View File
@@ -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)
}
}
+16
View File
@@ -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
+11
View File
@@ -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,
+32 -1
View File
@@ -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 <dir>/<window id>.set and we
# apply it at prompt time instead of typing a cd into the terminal: the
# command stays out of the history and a half typed multi-line command is
# not submitted. We publish our own directory the same way so that the panel
# can follow a cd made here.
if [[ -n "$KITTY_CWD_SYNC_DIR" && -n "$KITTY_WINDOW_ID" && -d "$KITTY_CWD_SYNC_DIR" ]]; then
_ksi_cwd_sync_file="$KITTY_CWD_SYNC_DIR/$KITTY_WINDOW_ID"
_ksi_cwd_sync_publish() {
builtin printf '%s' "$PWD" > "$_ksi_cwd_sync_file" 2> /dev/null
builtin return 0
}
_ksi_cwd_sync_apply() {
builtin local ret=$? target
if [[ -f "$_ksi_cwd_sync_file.set" ]]; then
IFS= builtin read -r target < "$_ksi_cwd_sync_file.set"
builtin command rm -f -- "$_ksi_cwd_sync_file.set"
if [[ -n "$target" && -d "$target" ]]; then
builtin cd -- "$target"
fi
fi
_ksi_cwd_sync_publish
builtin return $ret
}
_ksi_cwd_sync_publish
fi
builtin alias edit-in-kitty="kitten edit-in-kitty"
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
@@ -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 <dir>/<window id>.set and we
# apply it at prompt time instead of typing a cd into the terminal, see the
# bash integration for the rationale.
if set -q KITTY_CWD_SYNC_DIR; and set -q KITTY_WINDOW_ID; and test -d "$KITTY_CWD_SYNC_DIR"
function __ksi_cwd_sync_publish --on-event fish_prompt -d "Publish the working directory for the file manager panel"
printf '%s' "$PWD" > "$KITTY_CWD_SYNC_DIR/$KITTY_WINDOW_ID" 2> /dev/null
end
function __ksi_cwd_sync_apply --on-event fish_prompt -d "Apply a directory chosen in the file manager panel"
set --local file "$KITTY_CWD_SYNC_DIR/$KITTY_WINDOW_ID.set"
if test -f "$file"
set --local target (cat "$file")
rm -f -- "$file"
if test -n "$target" -a -d "$target"
builtin cd -- "$target"
end
end
__ksi_cwd_sync_publish
end
__ksi_cwd_sync_publish
end
# Note that neither alias nor function is recursive in fish so if the user defines an alias/function
# 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
+25
View File
@@ -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 <dir>/<window id>.set and we
# apply it at prompt time instead of typing a cd into the terminal, see the
# bash integration for the rationale.
if [[ -n $KITTY_CWD_SYNC_DIR && -n $KITTY_WINDOW_ID && -d $KITTY_CWD_SYNC_DIR ]]; then
builtin typeset -g _ksi_cwd_sync_file="$KITTY_CWD_SYNC_DIR/$KITTY_WINDOW_ID"
_ksi_cwd_sync_publish() { builtin print -rn -- "$PWD" >| "$_ksi_cwd_sync_file" 2> /dev/null; }
_ksi_cwd_sync_apply() {
builtin local -i ret=$?
builtin local target
if [[ -f "$_ksi_cwd_sync_file.set" ]]; then
IFS= builtin read -r target < "$_ksi_cwd_sync_file.set"
builtin command rm -f -- "$_ksi_cwd_sync_file.set"
if [[ -n $target && -d $target ]]; then
builtin cd -- "$target"
fi
fi
_ksi_cwd_sync_publish
builtin return ret
}
_ksi_cwd_sync_publish
precmd_functions+=(_ksi_cwd_sync_apply)
chpwd_functions+=(_ksi_cwd_sync_publish)
fi
# Enable terminal title changes.
if (( ! opt[(Ie)no-title] )); then
# We don't use `print -P` because it depends on prompt options, which