feat(file-manager): open files in a full-window editor tab

Enter on a file handed the editor command to the shell, so the panel closed
and had to be reopened, and a docked panel ran the editor squeezed into the
dock. Delegate to kitty's edit protocol instead: the editor opens in a new
tab with the whole window and the panel is redrawn with the same selection
when it exits.

The editor now comes from kitty's editor option. file-manager's editor,
open_with_sudo and --open-here are kept but ignored so existing configs and
mappings keep loading.
This commit is contained in:
BlackAngelTV committed 2026-11-06 08:41:18 +01:00
1 parent a12a05e666
commit 4fb1402d9e
4 files changed
+68 -160

No files matched your search

+18 -24
View File
@@ -17,7 +17,7 @@ perdre l'environnement, l'historique ni l'état de la session.
Lancer le panneau avec :code:`kitten file-manager`, ou depuis une Lancer le panneau avec :code:`kitten file-manager`, ou depuis une
:ref:`fenêtre dockée <docks>` pour l'avoir en permanence à côté du shell:: :ref:`fenêtre dockée <docks>` pour l'avoir en permanence à côté du shell::
map ctrl+shift+e launch --type=window-dock --dock-edge=left --dock-size=60 kitten file-manager --open-here map ctrl+shift+e launch --type=window-dock --dock-edge=left --dock-size=60 kitten file-manager
Il peut aussi tourner dans un :doc:`panneau du bureau </kittens/panel>` ou dans Il peut aussi tourner dans un :doc:`panneau du bureau </kittens/panel>` ou dans
n'importe quelle :term:`fenêtre kitty <window>` classique. n'importe quelle :term:`fenêtre kitty <window>` classique.
@@ -32,11 +32,10 @@ est passé en argument ou avec ``--start-dir``.
donc pas le répertoire du shell : utilisez :kbd:`Ctrl+Entrée` dans une donc pas le répertoire du shell : utilisez :kbd:`Ctrl+Entrée` dans une
fenêtre de shell. fenêtre de shell.
Les actions qui ferment le panneau (:kbd:`Entrée` et :kbd:`Ctrl+Entrée`) ne L'ouverture d'un fichier, elle, fonctionne partout : le panneau confie le
peuvent agir que sur la fenêtre qui l'a lancé : dans un dock, elles ferment fichier à kitty, qui lance l'éditeur dans un nouvel onglet. Le fichier
le panneau sans effet. Pour ouvrir des fichiers depuis un dock, lancez le dispose ainsi de toute la fenêtre même depuis un dock, et le panneau reprend
panneau avec ``--open-here`` : il ouvre alors l'éditeur dans sa propre la main à la fermeture de l'éditeur, avec la même sélection.
fenêtre et reprend la main une fois l'éditeur fermé.
Actions Actions
@@ -45,13 +44,15 @@ Actions
:kbd:`Entrée` :kbd:`Entrée`
Si la sélection est un répertoire, il devient le répertoire courant du Si la sélection est un répertoire, il devient le répertoire courant du
shell et le panneau se ferme. Si c'est un fichier, il est ouvert dans shell et le panneau se ferme. Si c'est un fichier, il est ouvert dans
l'éditeur configuré (:opt:`editor`, :envvar:`VISUAL` ou :envvar:`EDITOR`). l'éditeur de kitty (:opt:`editor`, :envvar:`VISUAL` ou :envvar:`EDITOR`)
Avec l'option ``open_with_sudo``, l'éditeur est lancé via :code:`sudo` pour dans un nouvel onglet ; le panneau reste ouvert et retrouve sa sélection
pouvoir modifier les fichiers appartenant à root. lorsque l'éditeur se ferme.
Avec ``--open-here``, l'éditeur est lancé dans la fenêtre du panneau et le Le nouvel onglet est ce qui donne au fichier toute la fenêtre : dans un
panneau reprend la main après sa fermeture, au lieu de rendre la commande au dock, exécuter l'éditeur dans le panneau le réduirait à la largeur du dock.
shell. C'est ce mode qu'il faut utiliser dans un dock. L'édition passe par le protocole d'édition de kitty, le fichier doit donc
être accessible en lecture et en écriture ; pour un fichier de root,
utilisez :code:`sudo -e` depuis le shell.
:kbd:`→` ou :kbd:`L` :kbd:`→` ou :kbd:`L`
descend dans le répertoire sélectionné sans toucher au shell. descend dans le répertoire sélectionné sans toucher au shell.
@@ -98,10 +99,6 @@ personnalisation::
# ~/.config/kitty/file-manager.conf # ~/.config/kitty/file-manager.conf
show_hidden yes show_hidden yes
sort_by mtime sort_by mtime
# Éditeur utilisé avec --open-here
editor nano
# Ouvrir les fichiers avec sudo (utile pour les fichiers de root)
open_with_sudo yes
map quit esc quit map quit esc quit
map toggle_hidden ctrl+h toggle_hidden map toggle_hidden ctrl+h toggle_hidden
map delete x delete map delete x delete
@@ -116,14 +113,11 @@ Deux réglages d'apparence sont aussi disponibles : ``show_hidden`` affiche les
entrées cachées à l'ouverture du panneau et ``sort_by`` vaut ``name`` (tri par entrées cachées à l'ouverture du panneau et ``sort_by`` vaut ``name`` (tri par
nom en ignorant la casse) ou ``mtime`` (tri par date de dernière modification). nom en ignorant la casse) ou ``mtime`` (tri par date de dernière modification).
``editor`` choisit l'éditeur utilisé en mode ``--open-here``, par exemple L'éditeur n'est pas choisi par le panneau : le fichier est confié à kitty, qui
``editor nano`` ou ``editor "code -w"``. Laissé vide, le panneau utilise utilise son option :opt:`editor` de :file:`kitty.conf`. Quand celle-ci vaut
:envvar:`VISUAL`, puis :envvar:`EDITOR`, puis :code:`vi`. :code:`.` (le défaut), :envvar:`VISUAL` puis :envvar:`EDITOR` sont utilisés,
avec repli sur le premier éditeur connu installé. Pour forcer nano, ajoutez
``open_with_sudo`` préfixe la commande d'édition par :code:`sudo`, ce qui :code:`editor nano` dans :file:`kitty.conf`.
permet d'ouvrir un fichier que l'utilisateur ne peut pas modifier, comme un
fichier de configuration système. Le mot de passe, s'il est demandé, se saisit
dans le shell qui héberge le panneau.
.. include:: /generated/conf-kitten-file_manager.rst .. include:: /generated/conf-kitten-file_manager.rst
+24 -50
View File
@@ -16,7 +16,6 @@ import (
"github.com/kovidgoyal/kitty/tools/config" "github.com/kovidgoyal/kitty/tools/config"
"github.com/kovidgoyal/kitty/tools/tui" "github.com/kovidgoyal/kitty/tools/tui"
"github.com/kovidgoyal/kitty/tools/tui/loop" "github.com/kovidgoyal/kitty/tools/tui/loop"
"github.com/kovidgoyal/kitty/tools/utils/shlex"
"github.com/kovidgoyal/kitty/tools/wcswidth" "github.com/kovidgoyal/kitty/tools/wcswidth"
) )
@@ -203,7 +202,6 @@ type Handler struct {
message string message string
result_action string result_action string
result_path string result_path string
open_here bool
shortcut_tracker config.ShortcutTracker shortcut_tracker config.ShortcutTracker
keyboard_shortcuts []*config.KeyAction keyboard_shortcuts []*config.KeyAction
} }
@@ -398,7 +396,7 @@ func (h *Handler) copy_selected_path() {
} }
// activate implements the primary action: the selected directory becomes the // activate implements the primary action: the selected directory becomes the
// working directory of the shell, the selected file is opened by the host. // working directory of the shell, the selected file is opened in the editor.
func (h *Handler) activate() { func (h *Handler) activate() {
e, ok := h.selected_entry() e, ok := h.selected_entry()
if !ok { if !ok {
@@ -410,46 +408,28 @@ func (h *Handler) activate() {
h.change_shell_dir_to(path) h.change_shell_dir_to(path)
return return
} }
if h.open_here { h.open_file(path)
h.open_file_in_panel(path) }
// edit_args is the client side of kitty's edit protocol. The terminal opens the
// editor in a new tab, which gives the file a whole window even when the panel
// is docked. The tab closes when the editor exits and the panel is redrawn in
// place, instead of handing the command to the shell and disappearing.
func edit_args(path string) []string {
return []string{"edit-in-kitty", "--type=tab", path}
}
func (h *Handler) open_file(path string) {
exe, err := os.Executable()
if err != nil {
h.message = err.Error()
h.draw_screen()
return return
} }
h.result_action, h.result_path = "open", path // The loop must give up the tty while edit-in-kitty talks to the terminal,
h.lp.Quit(0) // otherwise both processes compete for input and escape code responses.
} err = h.lp.SuspendAndRun(func() error {
cmd := exec.Command(exe, edit_args(path)...)
// editor_cmd resolves the editor used by --open-here. The panel's own `editor`
// option comes first because kitty's `editor` option is not visible to a
// process started with launch, then the usual environment variables.
func editor_cmd(conf *Config) []string {
for _, candidate := range []string{conf.Editor, os.Getenv("VISUAL"), os.Getenv("EDITOR")} {
if candidate == "" {
continue
}
if words, err := shlex.Split(candidate); err == nil && len(words) > 0 {
return words
}
}
return []string{"vi"}
}
// open_cmdline builds the command that opens path in the editor.
func open_cmdline(conf *Config, path string) []string {
cmdline := append(editor_cmd(conf), path)
if conf.Open_with_sudo {
// -- stops sudo from eating editor arguments that look like its own options.
cmdline = append([]string{"sudo", "--"}, cmdline...)
}
return cmdline
}
// open_file_in_panel runs the editor in the panel's own window. A docked panel
// has to do this itself: kitty never sends the result of a launch --type=window-dock
// back to the shell, so the panel would otherwise close without opening anything.
func (h *Handler) open_file_in_panel(path string) {
cmdline := open_cmdline(h.conf, path)
err := h.lp.SuspendAndRun(func() error {
cmd := exec.Command(cmdline[0], cmdline[1:]...)
cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr
return cmd.Run() return cmd.Run()
}) })
@@ -791,15 +771,9 @@ func (h *Handler) draw_screen() {
} }
} }
// result_payload is the JSON data handed over to the Python result handler. The // result_payload is the JSON data handed over to the Python result handler.
// sudo flag travels with the result so that handle_result does not have to read
// file-manager.conf a second time.
func (h *Handler) result_payload() map[string]string { func (h *Handler) result_payload() map[string]string {
data := map[string]string{"action": h.result_action, "path": h.result_path} return map[string]string{"action": h.result_action, "path": h.result_path}
if h.result_action == "open" && h.conf.Open_with_sudo {
data["sudo"] = "1"
}
return data
} }
func load_config(opts *Options) (*Config, error) { func load_config(opts *Options) (*Config, error) {
@@ -828,7 +802,7 @@ func main(_ *cli.Command, opts *Options, args []string) (rc int, err error) {
if err != nil { if err != nil {
return 1, err return 1, err
} }
h := &Handler{lp: lp, conf: conf, cwd: start_dir, show_hidden: opts.ShowHidden || conf.Show_hidden, open_here: opts.OpenHere} h := &Handler{lp: lp, conf: conf, cwd: start_dir, show_hidden: opts.ShowHidden || conf.Show_hidden}
h.keyboard_shortcuts = config.ResolveShortcuts(conf.KeyboardShortcuts) h.keyboard_shortcuts = config.ResolveShortcuts(conf.KeyboardShortcuts)
lp.MouseTrackingMode(loop.FULL_MOUSE_TRACKING) lp.MouseTrackingMode(loop.FULL_MOUSE_TRACKING)
+15 -37
View File
@@ -53,11 +53,10 @@ opt(
'editor', 'editor',
'', '',
long_text=""" long_text="""
Command used to open a file when the panel opens it itself, that is when Deprecated and ignored. Files are opened through kitty's edit protocol, so the
:code:`--open-here` is given. When empty, :envvar:`VISUAL` then editor is the :opt:`editor` option of :file:`kitty.conf`, with :envvar:`VISUAL`
:envvar:`EDITOR` are used, falling back to :code:`vi`. kitty's own :opt:`editor` then :envvar:`EDITOR` used when it is :code:`.` (the default). The option is
option is not visible to a panel started with :code:`launch`, so set this option still accepted so that existing configuration files keep loading.
when the panel runs in a dock and the two differ.
""", """,
) )
@@ -66,9 +65,9 @@ opt(
'no', 'no',
option_type='to_bool', option_type='to_bool',
long_text=""" long_text="""
Prefix the editor command with :code:`sudo` when opening a file, so that files Deprecated and ignored. kitty's edit protocol sends the file back when the
the user cannot write to, such as system configuration files, can still be editor exits and therefore needs a file the user can write to. Open privileged
edited. The password prompt, if any, appears in the shell that hosts the panel. files with :code:`sudo -e` from the shell instead.
""", """,
) )
@@ -95,11 +94,10 @@ map(
'activate enter activate', 'activate enter activate',
long_text=""" long_text="""
When the selection is a directory it becomes the working directory of the shell When the selection is a directory it becomes the working directory of the shell
that launched the panel. When it is a file, the shell receives the command that that launched the panel. When it is a file, the panel opens it in kitty's editor
opens it in the editor configured with the :opt:`editor` option, (:opt:`editor`, :envvar:`VISUAL` or :envvar:`EDITOR`) in a new tab, and is
:envvar:`VISUAL` or :envvar:`EDITOR`. With :code:`--open-here` the panel runs the drawn again with the same selection once the editor exits. The new tab is what
editor in its own window instead, which is what makes this action work in a gives the file a whole window even when the panel runs in a dock.
docked panel.
""", """,
) )
map( map(
@@ -154,9 +152,8 @@ Show hidden files when the panel opens.
--open-here --open-here
type=bool-set type=bool-set
Open files in the panel's own window instead of sending the editor command to Deprecated and ignored. Files are always opened in a new tab, so this flag is
the shell. Required in a window dock, where kitty never hands the result back to only accepted so that existing mappings keep working.
the shell.
--config -c --config -c
@@ -190,37 +187,18 @@ def change_directory(w: Any, path: str) -> None:
w.paste_text(cmd) w.paste_text(cmd)
def open_file(w: Any, path: str, use_sudo: bool = False) -> None:
# Run the editor in the shell that hosted the panel, like the cd action, so
# the file opens where the user already is instead of in a new tab.
from kitty.utils import get_editor
cmd = get_editor(path_to_edit=path)
if use_sudo:
# -- stops sudo from eating editor arguments that look like its own options.
cmd = ['sudo', '--'] + cmd
text = shlex.join(cmd)
if w.at_prompt:
w.write_to_child(text + '\r')
else:
w.paste_text(text)
@result_handler(has_ready_notification=True) @result_handler(has_ready_notification=True)
def handle_result(args: list[str], data: dict[str, Any], target_window_id: int, boss: BossType) -> None: def handle_result(args: list[str], data: dict[str, Any], target_window_id: int, boss: BossType) -> None:
if not data: if not data:
return return
action, path = data.get('action'), data.get('path') action, path = data.get('action'), data.get('path')
if not action or not path: if action != 'cd' or not path:
return return
w = boss.window_id_map.get(target_window_id) w = boss.window_id_map.get(target_window_id)
if w is None: if w is None:
boss.ring_bell_if_allowed() boss.ring_bell_if_allowed()
return return
if action == 'cd': change_directory(w, path)
change_directory(w, path)
elif action == 'open':
open_file(w, path, data.get('sudo') == '1')
help_text = 'Browse directories in a side panel and change the working directory of the shell without leaving it' help_text = 'Browse directories in a side panel and change the working directory of the shell without leaving it'
+11 -49
View File
@@ -180,37 +180,9 @@ func TestOpenWithSudoOption(t *testing.T) {
} }
} }
func TestEditorCommand(t *testing.T) { func TestEditArgs(t *testing.T) {
t.Setenv("VISUAL", "") got := edit_args("/tmp/a.py")
t.Setenv("EDITOR", "") want := []string{"edit-in-kitty", "--type=tab", "/tmp/a.py"}
if got := editor_cmd(NewConfig()); len(got) != 1 || got[0] != "vi" {
t.Fatalf("expected the vi fallback, got %#v", got)
}
t.Setenv("EDITOR", "nano")
if got := editor_cmd(NewConfig()); len(got) != 1 || got[0] != "nano" {
t.Fatalf("EDITOR must be used when the option is empty, got %#v", got)
}
t.Setenv("VISUAL", "code -w")
if got := editor_cmd(NewConfig()); len(got) != 2 || got[0] != "code" || got[1] != "-w" {
t.Fatalf("VISUAL must win over EDITOR, got %#v", got)
}
conf := NewConfig()
conf.Editor = "micro --wrap"
if got := editor_cmd(conf); len(got) != 2 || got[0] != "micro" || got[1] != "--wrap" {
t.Fatalf("the editor option must win over the environment, got %#v", got)
}
}
func TestOpenCmdline(t *testing.T) {
conf := NewConfig()
conf.Editor = "nano"
got := open_cmdline(conf, "/tmp/a.py")
if len(got) != 2 || got[0] != "nano" || got[1] != "/tmp/a.py" {
t.Fatalf("unexpected command line: %#v", got)
}
conf.Open_with_sudo = true
got = open_cmdline(conf, "/tmp/a.py")
want := []string{"sudo", "--", "nano", "/tmp/a.py"}
if len(got) != len(want) { if len(got) != len(want) {
t.Fatalf("expected %#v, got %#v", want, got) t.Fatalf("expected %#v, got %#v", want, got)
} }
@@ -222,32 +194,22 @@ func TestOpenCmdline(t *testing.T) {
} }
func TestLoadConfigReadsOpenWithSudo(t *testing.T) { func TestLoadConfigReadsOpenWithSudo(t *testing.T) {
// The option is ignored now, but old configuration files must keep loading.
dir := t.TempDir() dir := t.TempDir()
path := filepath.Join(dir, "file-manager.conf") path := filepath.Join(dir, "file-manager.conf")
if err := os.WriteFile(path, []byte("open_with_sudo yes\n"), 0o644); err != nil { if err := os.WriteFile(path, []byte("open_with_sudo yes\neditor nano\n"), 0o644); err != nil {
t.Fatal(err) t.Fatal(err)
} }
conf, err := load_config(&Options{Config: []string{path}}) if _, err := load_config(&Options{Config: []string{path}}); err != nil {
if err != nil {
t.Fatal(err) t.Fatal(err)
} }
if !conf.Open_with_sudo {
t.Fatal("open_with_sudo yes in file-manager.conf must enable sudo")
}
} }
func TestResultPayloadCarriesSudoOnlyWhenOpening(t *testing.T) { func TestResultPayload(t *testing.T) {
h := &Handler{conf: NewConfig(), result_action: "open", result_path: "/tmp/a.py"} h := &Handler{result_action: "cd", result_path: "/tmp"}
if _, ok := h.result_payload()["sudo"]; ok { got := h.result_payload()
t.Fatal("sudo must not be requested when the option is disabled") if len(got) != 2 || got["action"] != "cd" || got["path"] != "/tmp" {
} t.Fatalf("unexpected payload: %#v", got)
h.conf.Open_with_sudo = true
if got := h.result_payload()["sudo"]; got != "1" {
t.Fatalf("sudo must be requested when opening a file, got %q", got)
}
h.result_action = "cd"
if _, ok := h.result_payload()["sudo"]; ok {
t.Fatal("changing directory must never ask for sudo")
} }
} }