2 Commits
Author SHA1 Message Date
BlackAngelTV 4b59b3a375 docs(file-manager): describe the editor option and --open-here
Explain that Enter opens files in the configured editor, that
open_with_sudo prefixes it with sudo, and that a docked panel needs
--open-here since its results never reach the shell.
2026-11-05 15:48:01 +01:00
BlackAngelTV 86982b79be feat(file-manager): open files in the editor from the panel
Files used to open in a new tab, which loses the shell the user was
working in. Hand the editor command to that shell instead, optionally
through sudo for files owned by root.

A docked panel cannot do that: kitty never routes the result of a
launch --type=window-dock back to the shell, so Enter used to close the
panel without opening anything. Add --open-here, which suspends the
panel and runs the editor in its own window. The editor is resolved
from the new `editor` option, because kitty's own editor option is not
visible to a process started with launch.
2026-11-05 15:48:01 +01:00
5 changed files with 244 additions and 20 deletions

No files matched your search

+3 -1
View File
@@ -225,7 +225,9 @@ Detailed list of changes
- A new :doc:`file manager kitten <kittens/file-manager>`, run with
:code:`kitten file-manager`, that browses directories in a side panel and
changes the working directory of the shell that launched it without leaving
the shell. It opens files in a new tab, copies paths and creates, renames and
the shell. It opens files in the configured editor, optionally through
:code:`sudo`, and can open them in its own window with :code:`--open-here` so
that it stays usable in a dock. It also copies paths and creates, renames and
deletes entries after a confirmation
- :doc:`choose-files <kittens/choose-files>`: Fix concurrent custom preview
+29 -4
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
: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
map ctrl+shift+e launch --type=window-dock --dock-edge=left --dock-size=60 kitten file-manager --open-here
Il peut aussi tourner dans un :doc:`panneau du bureau </kittens/panel>` ou dans
n'importe quelle :term:`fenêtre kitty <window>` classique.
@@ -30,7 +30,13 @@ 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, ou ouvrez un nouvel onglet sur le répertoire visé.
fenêtre de shell.
Les actions qui ferment le panneau (:kbd:`Entrée` et :kbd:`Ctrl+Entrée`) ne
peuvent agir que sur la fenêtre qui l'a lancé : dans un dock, elles ferment
le panneau sans effet. Pour ouvrir des fichiers depuis un dock, lancez le
panneau avec ``--open-here`` : il ouvre alors l'éditeur dans sa propre
fenêtre et reprend la main une fois l'éditeur fermé.
Actions
@@ -38,8 +44,14 @@ Actions
:kbd:`Entrée`
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, un nouvel onglet est
ouvert sur son répertoire.
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`).
Avec l'option ``open_with_sudo``, l'éditeur est lancé via :code:`sudo` pour
pouvoir modifier les fichiers appartenant à root.
Avec ``--open-here``, l'éditeur est lancé dans la fenêtre du panneau et le
panneau reprend la main après sa fermeture, au lieu de rendre la commande au
shell. C'est ce mode qu'il faut utiliser dans un dock.
:kbd:`→` ou :kbd:`L`
descend dans le répertoire sélectionné sans toucher au shell.
@@ -86,6 +98,10 @@ personnalisation::
# ~/.config/kitty/file-manager.conf
show_hidden yes
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 toggle_hidden ctrl+h toggle_hidden
map delete x delete
@@ -100,6 +116,15 @@ 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
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
``editor nano`` ou ``editor "code -w"``. Laissé vide, le panneau utilise
:envvar:`VISUAL`, puis :envvar:`EDITOR`, puis :code:`vi`.
``open_with_sudo`` préfixe la commande d'édition par :code:`sudo`, ce qui
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/cli-kitten-file_manager.rst
+69 -2
View File
@@ -3,8 +3,10 @@
package file_manager
import (
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"sort"
"strings"
@@ -14,6 +16,7 @@ import (
"github.com/kovidgoyal/kitty/tools/config"
"github.com/kovidgoyal/kitty/tools/tui"
"github.com/kovidgoyal/kitty/tools/tui/loop"
"github.com/kovidgoyal/kitty/tools/utils/shlex"
"github.com/kovidgoyal/kitty/tools/wcswidth"
)
@@ -200,6 +203,7 @@ type Handler struct {
message string
result_action string
result_path string
open_here bool
shortcut_tracker config.ShortcutTracker
keyboard_shortcuts []*config.KeyAction
}
@@ -406,10 +410,62 @@ func (h *Handler) activate() {
h.change_shell_dir_to(path)
return
}
if h.open_here {
h.open_file_in_panel(path)
return
}
h.result_action, h.result_path = "open", path
h.lp.Quit(0)
}
// 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
return cmd.Run()
})
var ee *exec.ExitError
if err != nil && !errors.As(err, &ee) {
h.message = err.Error()
}
// The editor may have changed or removed the file, so refresh the listing.
if lerr := h.load(h.cwd); lerr != nil {
h.message = lerr.Error()
} else {
h.select_name(filepath.Base(path))
}
h.draw_screen()
}
// enter_dir browses into the selected directory inside the panel, leaving the
// working directory of the shell untouched.
func (h *Handler) enter_dir() {
@@ -735,6 +791,17 @@ func (h *Handler) draw_screen() {
}
}
// result_payload is the JSON data handed over to the Python result handler. The
// 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 {
data := 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) {
ans := NewConfig()
p := config.ConfigParser{LineHandler: ans.Parse}
@@ -761,7 +828,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, open_here: opts.OpenHere}
h.keyboard_shortcuts = config.ResolveShortcuts(conf.KeyboardShortcuts)
lp.MouseTrackingMode(loop.FULL_MOUSE_TRACKING)
@@ -783,7 +850,7 @@ func main(_ *cli.Command, opts *Options, args []string) (rc int, err error) {
rc = lp.ExitCode()
if h.result_action != "" {
output := tui.KittenOutputSerializer()
if s, serr := output(map[string]string{"action": h.result_action, "path": h.result_path}); serr == nil {
if s, serr := output(h.result_payload()); serr == nil {
fmt.Println(s)
}
}
+53 -13
View File
@@ -1,7 +1,6 @@
#!/usr/bin/env python
# License: GPL v3 Copyright: 2026, FWS
import os
import shlex
import sys
from functools import partial
@@ -48,6 +47,33 @@ sorted by last modification time, most recent first.
egr()
agr('opening', 'Opening files')
opt(
'editor',
'',
long_text="""
Command used to open a file when the panel opens it itself, that is when
:code:`--open-here` is given. When empty, :envvar:`VISUAL` then
:envvar:`EDITOR` are used, falling back to :code:`vi`. kitty's own :opt:`editor`
option is not visible to a panel started with :code:`launch`, so set this option
when the panel runs in a dock and the two differ.
""",
)
opt(
'open_with_sudo',
'no',
option_type='to_bool',
long_text="""
Prefix the editor command with :code:`sudo` when opening a file, so that files
the user cannot write to, such as system configuration files, can still be
edited. The password prompt, if any, appears in the shell that hosts the panel.
""",
)
egr()
agr('shortcuts', 'Keyboard shortcuts')
map('Quit without changing directory', 'quit q quit')
@@ -69,7 +95,11 @@ map(
'activate enter activate',
long_text="""
When the selection is a directory it becomes the working directory of the shell
that launched the panel. When it is a file, a new tab is opened on its directory.
that launched the panel. When it is a file, the shell receives the command that
opens it in the editor configured with the :opt:`editor` option,
:envvar:`VISUAL` or :envvar:`EDITOR`. With :code:`--open-here` the panel runs the
editor in its own window instead, which is what makes this action work in a
docked panel.
""",
)
map(
@@ -122,6 +152,13 @@ type=bool-set
Show hidden files when the panel opens.
--open-here
type=bool-set
Open files in the panel's own window instead of sending the editor command to
the shell. Required in a window dock, where kitty never hands the result back to
the shell.
--config -c
type=list
completion=type:file ext:conf group:"Config files" kwds:none,NONE
@@ -153,17 +190,20 @@ def change_directory(w: Any, path: str) -> None:
w.paste_text(cmd)
def open_in_new_tab(boss: BossType, w: Any, path: str) -> None:
from kitty.tabs import SpecialWindow
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
tab = w.tabref()
tm = tab.tab_manager_ref() if tab is not None else None
if tm is None:
boss.ring_bell_if_allowed()
return
cwd = os.path.dirname(path) or None
shell = os.environ.get('SHELL') or '/bin/sh'
tm.new_tab(SpecialWindow(cmd=[shell], cwd=cwd))
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)
@@ -180,7 +220,7 @@ def handle_result(args: list[str], data: dict[str, Any], target_window_id: int,
if action == 'cd':
change_directory(w, path)
elif action == 'open':
open_in_new_tab(boss, w, path)
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'
+90
View File
@@ -161,6 +161,96 @@ func TestResolveStartDirAcceptsFiles(t *testing.T) {
}
}
func TestOpenWithSudoOption(t *testing.T) {
c := NewConfig()
if c.Open_with_sudo {
t.Fatal("files must not be opened with sudo by default")
}
if err := c.Parse("open_with_sudo", "yes"); err != nil {
t.Fatal(err)
}
if !c.Open_with_sudo {
t.Fatal("open_with_sudo = yes must enable sudo")
}
if err := c.Parse("open_with_sudo", "no"); err != nil {
t.Fatal(err)
}
if c.Open_with_sudo {
t.Fatal("open_with_sudo = no must disable sudo")
}
}
func TestEditorCommand(t *testing.T) {
t.Setenv("VISUAL", "")
t.Setenv("EDITOR", "")
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) {
t.Fatalf("expected %#v, got %#v", want, got)
}
for i := range want {
if got[i] != want[i] {
t.Fatalf("expected %#v, got %#v", want, got)
}
}
}
func TestLoadConfigReadsOpenWithSudo(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "file-manager.conf")
if err := os.WriteFile(path, []byte("open_with_sudo yes\n"), 0o644); err != nil {
t.Fatal(err)
}
conf, err := load_config(&Options{Config: []string{path}})
if err != nil {
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) {
h := &Handler{conf: NewConfig(), result_action: "open", result_path: "/tmp/a.py"}
if _, ok := h.result_payload()["sudo"]; ok {
t.Fatal("sudo must not be requested when the option is disabled")
}
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")
}
}
func TestTruncateToWidth(t *testing.T) {
if got := truncate_to_width("abcdef", 3); got != "ab\u2026" {
t.Fatalf("unexpected truncation %q", got)