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.
This commit is contained in:
3 files changed
+212
-15
No files matched your search
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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'
|
||||
|
||||
@@ -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)
|
||||
|
||||
Reference in new issue
Block a user