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

+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)
}
}