feat(file-manager): add a keyboard driven file manager kitten

Navigating a project from the shell meant chaining cd commands or leaving the
session for ranger or yazi, which isolates the environment and history. The new
kitten browses directories in a side panel on top of the existing panel and
tui/loop infrastructure and hands the selected directory back to the shell, so
the session stays intact.
This commit is contained in:
BlackAngelTV committed 2026-11-05 10:48:27 +01:00
1 parent 4d10615cc4
commit 01c1531119
7 files changed
+1278

No files matched your search

+6
View File
@@ -222,6 +222,12 @@ Detailed list of changes
0.50.1 [unreleased]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
- 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
deletes entries after a confirmation
- :doc:`choose-files <kittens/choose-files>`: Fix concurrent custom preview
commands occasionally receiving the path of a different file.
+105
View File
@@ -0,0 +1,105 @@
.. _file_manager:
Gestionnaire de fichiers
=========================
.. only:: man
Aperçu
------
Le gestionnaire de fichiers affiche le contenu d'un répertoire dans un panneau
latéral, pilotable entièrement au clavier, et change le répertoire courant du
shell qui l'a lancé. Il remplace la plupart des :code:`cd` : on descend dans
l'arborescence, on valide, le panneau se ferme et le shell se déplace, sans
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
Il peut aussi tourner dans un :doc:`panneau du bureau </kittens/panel>` ou dans
n'importe quelle :term:`fenêtre kitty <window>` classique.
Le répertoire de départ est celui de la fenêtre courante, sauf si un répertoire
est passé en argument ou avec ``--start-dir``.
.. note::
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é.
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.
:kbd:`→` ou :kbd:`L`
descend dans le répertoire sélectionné sans toucher au shell.
:kbd:`←`, :kbd:`Retour arrière` ou :kbd:`H`
remonte au répertoire parent.
:kbd:`Ctrl+Entrée` ou :kbd:`C`
déplace le shell vers le répertoire affiché, sans tenir compte de la
sélection.
:kbd:`N` et :kbd:`Maj+N`
créent un fichier, respectivement un répertoire, dans le répertoire
affiché. Le nom se saisit dans la ligne d'état.
:kbd:`R`
renomme l'entrée sélectionnée.
:kbd:`D`
supprime l'entrée sélectionnée après confirmation par :kbd:`y`. Les
répertoires ne sont jamais supprimés récursivement : un répertoire non vide
provoque une erreur.
:kbd:`Y`
copie le chemin de la sélection dans le presse-papiers.
:kbd:`.`
affiche ou masque les entrées cachées.
:kbd:`Échap` ou :kbd:`Q`
ferme le panneau sans rien changer.
.. _file-manager-shortcuts:
Raccourcis et configuration
-----------------------------
Tous les raccourcis sont configurables dans :file:`file-manager.conf`, dans le
répertoire de configuration de kitty, avec la même syntaxe que les mappages de
:file:`kitty.conf`. La valeur par défaut, suivie d'un exemple de
personnalisation::
# ~/.config/kitty/file-manager.conf
show_hidden yes
sort_by mtime
map quit esc quit
map toggle_hidden ctrl+h toggle_hidden
map delete x delete
Les actions disponibles sont :code:`quit`, :code:`move_up`, :code:`move_down`,
:code:`page_up`, :code:`page_down`, :code:`home`, :code:`end`,
:code:`activate`, :code:`enter_dir`, :code:`parent_dir`, :code:`cd_here`,
:code:`toggle_hidden`, :code:`create_file`, :code:`create_dir`,
:code:`rename`, :code:`delete`, :code:`copy_path` et :code:`refresh`.
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).
.. include:: /generated/conf-kitten-file_manager.rst
.. include:: /generated/cli-kitten-file_manager.rst
View File
Whitespace-only changes.
+794
View File
@@ -0,0 +1,794 @@
// License: GPLv3 Copyright: 2026, FWS
package file_manager
import (
"fmt"
"os"
"path/filepath"
"sort"
"strings"
"time"
"github.com/kovidgoyal/kitty/tools/cli"
"github.com/kovidgoyal/kitty/tools/config"
"github.com/kovidgoyal/kitty/tools/tui"
"github.com/kovidgoyal/kitty/tools/tui/loop"
"github.com/kovidgoyal/kitty/tools/wcswidth"
)
var _ = fmt.Print
// Entry is a single item of the listing. ModTime is kept as a unix timestamp
// so that sorting by date does not require stat()ing every entry again.
type Entry struct {
Name string
IsDir bool
ModTime int64
}
type input_purpose int
const (
input_none input_purpose = iota
input_create_file
input_create_dir
input_rename
)
// Pure helpers, kept free of terminal state so that they can be unit tested
// without a tty.
func is_hidden_name(name string) bool {
return strings.HasPrefix(name, ".")
}
func sort_entries(entries []Entry, sort_by string) {
sort.SliceStable(entries, func(i, j int) bool {
a, b := entries[i], entries[j]
if a.IsDir != b.IsDir {
return a.IsDir
}
if sort_by == "mtime" && a.ModTime != b.ModTime {
return a.ModTime > b.ModTime
}
return strings.ToLower(a.Name) < strings.ToLower(b.Name)
})
}
func read_dir(dir string, show_hidden bool, sort_by string) ([]Entry, error) {
items, err := os.ReadDir(dir)
if err != nil {
return nil, err
}
entries := make([]Entry, 0, len(items))
for _, item := range items {
name := item.Name()
if !show_hidden && is_hidden_name(name) {
continue
}
e := Entry{Name: name, IsDir: item.IsDir()}
if info, ierr := item.Info(); ierr == nil {
e.ModTime = info.ModTime().Unix()
}
entries = append(entries, e)
}
sort_entries(entries, sort_by)
return entries, nil
}
func entry_path(dir, name string) string {
return filepath.Join(dir, name)
}
func parent_of(dir string) string {
return filepath.Dir(dir)
}
func validate_entry_name(name string) error {
if name == "" || name == "." || name == ".." {
return fmt.Errorf("A file name is required")
}
if strings.ContainsRune(name, '/') || strings.ContainsRune(name, 0) || strings.ContainsRune(name, os.PathSeparator) {
return fmt.Errorf("%#v is not a valid file name as it contains a path separator", name)
}
return nil
}
func create_file(dir, name string) (string, error) {
if err := validate_entry_name(name); err != nil {
return "", err
}
path := entry_path(dir, name)
f, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o644)
if err != nil {
return "", err
}
if err = f.Close(); err != nil {
return "", err
}
return path, nil
}
func create_subdir(dir, name string) (string, error) {
if err := validate_entry_name(name); err != nil {
return "", err
}
path := entry_path(dir, name)
if err := os.Mkdir(path, 0o755); err != nil {
return "", err
}
return path, nil
}
func rename_entry(dir, old_name, new_name string) (string, error) {
if err := validate_entry_name(new_name); err != nil {
return "", err
}
if old_name == new_name {
return entry_path(dir, old_name), nil
}
dest := entry_path(dir, new_name)
if _, err := os.Lstat(dest); err == nil {
return "", fmt.Errorf("%#v already exists", new_name)
}
if err := os.Rename(entry_path(dir, old_name), dest); err != nil {
return "", err
}
return dest, nil
}
// delete_entry removes a file, a symlink or an empty directory. Recursive
// deletion is deliberately not done here so that a misplaced keypress cannot
// wipe out a tree of files.
func delete_entry(dir, name string) error {
if name == "" || name == "." || name == ".." {
return fmt.Errorf("Cannot delete %#v", name)
}
return os.Remove(entry_path(dir, name))
}
func resolve_start_dir(candidate string) (string, error) {
if candidate == "" {
cwd, err := os.Getwd()
if err != nil {
return "", err
}
candidate = cwd
}
abs, err := filepath.Abs(candidate)
if err != nil {
return "", err
}
info, err := os.Stat(abs)
if err != nil {
return "", err
}
if !info.IsDir() {
abs = filepath.Dir(abs)
}
return abs, nil
}
func truncate_to_width(s string, max_width int) string {
if max_width <= 0 {
return ""
}
if wcswidth.Stringwidth(s) <= max_width {
return s
}
runes := []rune(s)
for len(runes) > 0 && wcswidth.Stringwidth(string(runes))+1 > max_width {
runes = runes[:len(runes)-1]
}
return string(runes) + "\u2026"
}
type Handler struct {
lp *loop.Loop
screen_size loop.ScreenSize
conf *Config
cwd string
entries []Entry
selected int
scroll int
show_hidden bool
input_purpose input_purpose
text_buffer string
rename_source string
confirm_name string
message string
result_action string
result_path string
shortcut_tracker config.ShortcutTracker
keyboard_shortcuts []*config.KeyAction
}
func (h *Handler) initialize() (string, error) {
sz, err := h.lp.ScreenSize()
if err != nil {
return "", err
}
h.screen_size = sz
h.lp.SetCursorVisible(false)
h.lp.AllowLineWrapping(false)
h.lp.SetWindowTitle("File manager")
if err = h.load(h.cwd); err != nil {
return "", err
}
h.draw_screen()
return "", nil
}
// 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.
func (h *Handler) load(dir string) error {
entries, err := read_dir(dir, h.show_hidden, h.conf.Sort_by)
if err != nil {
return err
}
h.cwd = dir
h.entries = entries
if h.selected >= len(entries) {
h.selected = max(0, len(entries)-1)
}
if h.scroll > h.selected {
h.scroll = h.selected
}
return nil
}
func (h *Handler) select_name(name string) {
if name == "" {
return
}
for i, e := range h.entries {
if e.Name == name {
h.selected = i
return
}
}
}
func (h *Handler) selected_entry() (Entry, bool) {
if h.selected < 0 || h.selected >= len(h.entries) {
return Entry{}, false
}
return h.entries[h.selected], true
}
func (h *Handler) reload() {
name := ""
if e, ok := h.selected_entry(); ok {
name = e.Name
}
if err := h.load(h.cwd); err != nil {
h.message = err.Error()
h.draw_screen()
return
}
h.select_name(name)
h.message = ""
h.draw_screen()
}
func (h *Handler) change_dir(dir string) {
if err := h.load(dir); err != nil {
h.message = err.Error()
h.draw_screen()
return
}
h.selected, h.scroll, h.message = 0, 0, ""
h.draw_screen()
}
func (h *Handler) move_selection(delta int) {
if len(h.entries) == 0 {
return
}
h.selected += delta
h.selected = max(0, h.selected)
h.selected = min(h.selected, len(h.entries)-1)
h.draw_screen()
}
func (h *Handler) cancel_input() {
h.input_purpose = input_none
h.text_buffer = ""
h.rename_source = ""
h.message = ""
h.draw_screen()
}
func (h *Handler) start_input(purpose input_purpose) {
h.input_purpose = purpose
h.text_buffer = ""
h.message = ""
h.draw_screen()
}
func (h *Handler) start_rename() {
e, ok := h.selected_entry()
if !ok {
h.lp.Beep()
return
}
h.input_purpose = input_rename
h.rename_source = e.Name
h.text_buffer = e.Name
h.message = ""
h.draw_screen()
}
// commit_input applies the pending create/rename operation. The name is
// trimmed because a trailing space is almost never intended in a file name.
func (h *Handler) commit_input() {
name := strings.TrimSpace(h.text_buffer)
purpose := h.input_purpose
source := h.rename_source
h.input_purpose = input_none
h.text_buffer = ""
h.rename_source = ""
var err error
var created string
switch purpose {
case input_create_file:
created, err = create_file(h.cwd, name)
case input_create_dir:
created, err = create_subdir(h.cwd, name)
case input_rename:
created, err = rename_entry(h.cwd, source, name)
}
if err != nil {
h.message = err.Error()
h.draw_screen()
return
}
if err = h.load(h.cwd); err != nil {
h.message = err.Error()
h.draw_screen()
return
}
h.select_name(filepath.Base(created))
h.message = ""
h.draw_screen()
}
func (h *Handler) start_delete() {
e, ok := h.selected_entry()
if !ok {
h.lp.Beep()
return
}
h.confirm_name = e.Name
h.message = ""
h.draw_screen()
}
func (h *Handler) perform_delete() {
name := h.confirm_name
h.confirm_name = ""
if err := delete_entry(h.cwd, name); err != nil {
h.message = err.Error()
h.draw_screen()
return
}
if err := h.load(h.cwd); err != nil {
h.message = err.Error()
}
h.select_name(name)
h.message = fmt.Sprintf("Deleted %s", name)
h.draw_screen()
}
func (h *Handler) copy_selected_path() {
path := h.cwd
if e, ok := h.selected_entry(); ok {
path = entry_path(h.cwd, e.Name)
}
h.lp.CopyTextToClipboard(path)
h.message = fmt.Sprintf("Copied %s", path)
h.draw_screen()
}
// activate implements the primary action: the selected directory becomes the
// working directory of the shell, the selected file is opened by the host.
func (h *Handler) activate() {
e, ok := h.selected_entry()
if !ok {
h.lp.Beep()
return
}
path := entry_path(h.cwd, e.Name)
if e.IsDir {
h.change_shell_dir_to(path)
return
}
h.result_action, h.result_path = "open", path
h.lp.Quit(0)
}
// enter_dir browses into the selected directory inside the panel, leaving the
// working directory of the shell untouched.
func (h *Handler) enter_dir() {
e, ok := h.selected_entry()
if !ok || !e.IsDir {
h.lp.Beep()
return
}
h.change_dir(entry_path(h.cwd, e.Name))
}
func (h *Handler) change_shell_dir_to(path string) {
h.result_action, h.result_path = "cd", path
h.lp.Quit(0)
}
// change_shell_dir ends the kitten with a request to change the directory of
// the shell that hosted it, to the selected directory, or to the one being
// browsed when a file is selected.
func (h *Handler) change_shell_dir() {
path := h.cwd
if e, ok := h.selected_entry(); ok && e.IsDir {
path = entry_path(h.cwd, e.Name)
}
h.change_shell_dir_to(path)
}
func (h *Handler) perform_action(name string) {
switch name {
case "quit":
h.lp.Quit(0)
case "move_up":
h.move_selection(-1)
case "move_down":
h.move_selection(1)
case "page_up":
h.move_selection(-max(1, int(h.screen_size.HeightCells)-3))
case "page_down":
h.move_selection(max(1, int(h.screen_size.HeightCells)-3))
case "home":
h.selected = 0
h.draw_screen()
case "end":
if len(h.entries) > 0 {
h.selected = len(h.entries) - 1
}
h.draw_screen()
case "parent_dir":
h.change_dir(parent_of(h.cwd))
case "activate":
h.activate()
case "enter_dir":
h.enter_dir()
case "cd_here":
h.change_shell_dir()
case "toggle_hidden":
h.show_hidden = !h.show_hidden
h.reload()
case "create_file":
h.start_input(input_create_file)
case "create_dir":
h.start_input(input_create_dir)
case "rename":
h.start_rename()
case "delete":
h.start_delete()
case "copy_path":
h.copy_selected_path()
case "refresh":
h.reload()
}
}
func (h *Handler) handle_input_key(ev *loop.KeyEvent) error {
switch {
case ev.MatchesPressOrRepeat("escape"):
ev.Handled = true
h.cancel_input()
case ev.MatchesPressOrRepeat("enter"):
ev.Handled = true
h.commit_input()
case ev.MatchesPressOrRepeat("backspace"):
ev.Handled = true
if h.text_buffer != "" {
g := wcswidth.SplitIntoGraphemes(h.text_buffer)
h.text_buffer = strings.Join(g[:len(g)-1], "")
}
h.draw_screen()
}
return nil
}
func (h *Handler) handle_confirm_key(ev *loop.KeyEvent) error {
switch {
case ev.MatchesPressOrRepeat("escape"):
ev.Handled = true
h.confirm_name = ""
h.draw_screen()
case ev.MatchesPressOrRepeat("enter"):
ev.Handled = true
h.perform_delete()
}
return nil
}
func (h *Handler) on_key_event(ev *loop.KeyEvent) error {
if h.input_purpose != input_none {
return h.handle_input_key(ev)
}
if h.confirm_name != "" {
return h.handle_confirm_key(ev)
}
if ac := h.shortcut_tracker.Match(ev, h.keyboard_shortcuts); ac != nil {
ev.Handled = true
h.perform_action(ac.Name)
return nil
}
// Fallbacks so the panel stays usable when the user has replaced the
// default shortcuts wholesale.
switch {
case ev.MatchesPressOrRepeat("escape"):
ev.Handled = true
h.perform_action("quit")
case ev.MatchesPressOrRepeat("enter"):
ev.Handled = true
h.perform_action("activate")
case ev.MatchesPressOrRepeat("up"):
ev.Handled = true
h.perform_action("move_up")
case ev.MatchesPressOrRepeat("down"):
ev.Handled = true
h.perform_action("move_down")
case ev.MatchesPressOrRepeat("backspace"):
ev.Handled = true
h.perform_action("parent_dir")
case ev.MatchesPressOrRepeat("right"):
ev.Handled = true
h.perform_action("enter_dir")
case ev.MatchesPressOrRepeat("left"):
ev.Handled = true
h.perform_action("parent_dir")
case ev.MatchesPressOrRepeat("page_up"):
ev.Handled = true
h.perform_action("page_up")
case ev.MatchesPressOrRepeat("page_down"):
ev.Handled = true
h.perform_action("page_down")
}
return nil
}
func (h *Handler) on_text(text string, from_key_event bool, in_bracketed_paste bool) error {
if h.confirm_name != "" {
switch strings.ToLower(strings.TrimSpace(text)) {
case "y":
h.perform_delete()
case "n":
h.confirm_name = ""
h.draw_screen()
}
return nil
}
if h.input_purpose != input_none {
h.text_buffer += text
h.draw_screen()
}
return nil
}
func (h *Handler) on_resize(old, new_size loop.ScreenSize) error {
h.screen_size = new_size
h.draw_screen()
return nil
}
func (h *Handler) row_to_entry(cell_y int) int {
screen_row := cell_y + 1
list_start := 2
list_height := int(h.screen_size.HeightCells) - 1 - list_start
if screen_row < list_start || screen_row >= list_start+list_height {
return -1
}
idx := h.scroll + (screen_row - list_start)
if idx < 0 || idx >= len(h.entries) {
return -1
}
return idx
}
func (h *Handler) on_mouse_event(ev *loop.MouseEvent) error {
switch ev.Event_type {
case loop.MOUSE_CLICK:
if ev.Buttons&loop.LEFT_MOUSE_BUTTON != 0 {
if idx := h.row_to_entry(ev.Cell.Y); idx >= 0 {
h.selected = idx
h.draw_screen()
}
}
case loop.MOUSE_MOVE:
h.lp.ClearPointerShapes()
if h.row_to_entry(ev.Cell.Y) >= 0 {
h.lp.PushPointerShape(loop.POINTER_POINTER)
}
}
return nil
}
func (h *Handler) entry_text(e Entry, width int) string {
name := e.Name
if e.IsDir {
name += "/"
}
return " " + truncate_to_width(name, width-2)
}
func (h *Handler) padded_entry_text(e Entry, width int) string {
text := h.entry_text(e, width)
if pad := width - wcswidth.Stringwidth(text); pad > 0 {
text += strings.Repeat(" ", pad)
}
return text
}
func (h *Handler) input_prompt() string {
switch h.input_purpose {
case input_create_file:
return "New file:"
case input_create_dir:
return "New directory:"
case input_rename:
return fmt.Sprintf("Rename %s to:", h.rename_source)
}
return ""
}
func (h *Handler) status_text() string {
if h.message != "" {
return " " + truncate_to_width(h.message, max(1, int(h.screen_size.WidthCells)-1))
}
if len(h.entries) == 0 {
return " Empty directory"
}
e, ok := h.selected_entry()
if !ok {
return " Empty directory"
}
kind := "file"
if e.IsDir {
kind = "directory"
}
return fmt.Sprintf(" %d/%d - %s - modified %s", h.selected+1, len(h.entries), kind, time.Unix(e.ModTime, 0).Format("2006-01-02 15:04"))
}
func (h *Handler) draw_screen() {
h.lp.StartAtomicUpdate()
defer h.lp.EndAtomicUpdate()
h.lp.ClearScreen()
width := int(h.screen_size.WidthCells)
height := int(h.screen_size.HeightCells)
if width < 10 || height < 4 {
return
}
h.lp.MoveCursorTo(1, 1)
h.lp.QueueWriteString(h.lp.SprintStyled("bold fg=bright-green", truncate_to_width(h.cwd, width)))
list_start := 2
status_y := height - 1
list_height := status_y - list_start
if list_height < 1 {
list_height = 1
}
if len(h.entries) > 0 {
h.selected = max(0, min(h.selected, len(h.entries)-1))
} else {
h.selected, h.scroll = 0, 0
}
if h.selected < h.scroll {
h.scroll = h.selected
}
if h.selected >= h.scroll+list_height {
h.scroll = h.selected - list_height + 1
}
h.scroll = max(0, min(h.scroll, max(0, len(h.entries)-list_height)))
for row := 0; row < list_height; row++ {
idx := h.scroll + row
if idx >= len(h.entries) {
break
}
e := h.entries[idx]
h.lp.MoveCursorTo(1, list_start+row)
switch {
case idx == h.selected:
h.lp.QueueWriteString(h.lp.SprintStyled("reverse", h.padded_entry_text(e, width)))
case e.IsDir:
h.lp.QueueWriteString(h.lp.SprintStyled("fg=bright-blue", h.entry_text(e, width)))
default:
h.lp.QueueWriteString(h.entry_text(e, width))
}
}
h.lp.MoveCursorTo(1, status_y)
h.lp.QueueWriteString(h.lp.SprintStyled("dim", h.status_text()))
h.lp.MoveCursorTo(1, height)
switch {
case h.input_purpose != input_none:
prompt := h.input_prompt() + " "
h.lp.QueueWriteString(h.lp.SprintStyled("fg=bright-yellow", prompt))
h.lp.QueueWriteString(h.text_buffer)
h.lp.SetCursorVisible(true)
h.lp.MoveCursorTo(1+wcswidth.Stringwidth(prompt+h.text_buffer), height)
case h.confirm_name != "":
h.lp.SetCursorVisible(false)
h.lp.QueueWriteString(h.lp.SprintStyled("bold fg=bright-red", fmt.Sprintf("Delete %s? [y/N] ", h.confirm_name)))
default:
h.lp.SetCursorVisible(false)
hints := "Enter: cd/open ->: enter <-: up .: hidden n: new file r: rename d: delete y: copy q: quit"
h.lp.QueueWriteString(h.lp.SprintStyled("dim", truncate_to_width(hints, width)))
}
}
func load_config(opts *Options) (*Config, error) {
ans := NewConfig()
p := config.ConfigParser{LineHandler: ans.Parse}
if err := p.LoadConfig("file-manager.conf", opts.Config, opts.Override); err != nil {
return nil, err
}
return ans, nil
}
func main(_ *cli.Command, opts *Options, args []string) (rc int, err error) {
conf, err := load_config(opts)
if err != nil {
return 1, err
}
candidate := opts.StartDir
if len(args) > 0 {
candidate = args[0]
}
start_dir, err := resolve_start_dir(candidate)
if err != nil {
return 1, err
}
lp, err := loop.New()
if err != nil {
return 1, err
}
h := &Handler{lp: lp, conf: conf, cwd: start_dir, show_hidden: opts.ShowHidden || conf.Show_hidden}
h.keyboard_shortcuts = config.ResolveShortcuts(conf.KeyboardShortcuts)
lp.MouseTrackingMode(loop.FULL_MOUSE_TRACKING)
lp.OnInitialize = func() (string, error) { return h.initialize() }
lp.OnFinalize = func() string { return "" }
lp.OnKeyEvent = h.on_key_event
lp.OnText = h.on_text
lp.OnResize = h.on_resize
lp.OnMouseEvent = h.on_mouse_event
if err = lp.Run(); err != nil {
return 1, err
}
if ds := lp.DeathSignalName(); ds != "" {
fmt.Println("Killed by signal:", ds)
lp.KillIfSignalled()
return
}
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 {
fmt.Println(s)
}
}
return
}
func EntryPoint(parent *cli.Command) {
create_cmd(parent, main)
}
+199
View File
@@ -0,0 +1,199 @@
#!/usr/bin/env python
# License: GPL v3 Copyright: 2026, FWS
import os
import shlex
import sys
from functools import partial
from typing import Any
from kitty.conf.types import Definition
from kitty.constants import appname
from kitty.simple_cli_definitions import CONFIG_HELP, CompletionSpec
from kitty.typing_compat import BossType
from ..tui.handler import result_handler
definition = Definition(
'!kittens.file_manager',
)
agr = definition.add_group
egr = definition.end_group
opt = definition.add_option
map = definition.add_map
agr('appearance', 'Appearance')
opt(
'show_hidden',
'no',
option_type='to_bool',
long_text="""
Show entries whose name starts with a full stop when the panel opens. The setting
can be toggled at runtime with the :ref:`toggle_hidden <file-manager-shortcuts>`
shortcut.
""",
)
opt(
'sort_by',
'name',
long_text="""
How to order entries. :code:`name` lists directories first, then files, both
sorted by name ignoring case. :code:`mtime` lists directories first, then files
sorted by last modification time, most recent first.
""",
)
egr()
agr('shortcuts', 'Keyboard shortcuts')
map('Quit without changing directory', 'quit q quit')
map('Quit without changing directory', 'quit esc quit')
map('Move selection up', 'move_up up move_up')
map('Move selection up', 'move_up --allow-fallback=shifted,ascii k move_up')
map('Move selection down', 'move_down down move_down')
map('Move selection down', 'move_down --allow-fallback=shifted,ascii j move_down')
map('Move selection up by a page', 'page_up page_up page_up')
map('Move selection up by a page', 'page_up --allow-fallback=shifted,ascii ctrl+b page_up')
map('Move selection down by a page', 'page_down page_down page_down')
map('Move selection down by a page', 'page_down --allow-fallback=shifted,ascii ctrl+f page_down')
map('Select first entry', 'home home home')
map('Select first entry', 'home --allow-fallback=shifted,ascii g home')
map('Select last entry', 'end end end')
map('Select last entry', 'end shift+g end')
map(
'Change shell directory or open selection',
'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.
""",
)
map(
'Browse into the selected directory',
'enter_dir right enter_dir',
long_text="""
Move the panel into the selected directory without changing the shell's working
directory. Use the :ref:`activate <file-manager-shortcuts>` shortcut to also
change the shell's directory.
""",
)
map('Browse into the selected directory', 'enter_dir --allow-fallback=shifted,ascii l enter_dir')
map('Browse into the parent directory', 'parent_dir left parent_dir')
map('Browse into the parent directory', 'parent_dir backspace parent_dir')
map('Browse into the parent directory', 'parent_dir --allow-fallback=shifted,ascii h parent_dir')
map(
'Change shell directory to the directory being browsed',
'cd_here ctrl+enter cd_here',
long_text="""
Changes the shell's working directory to the directory currently shown in the
panel, regardless of the selection.
""",
)
map('Change shell directory to the directory being browsed', 'cd_here --allow-fallback=shifted,ascii c cd_here')
map('Toggle display of hidden entries', 'toggle_hidden --allow-fallback=shifted,ascii . toggle_hidden')
map('Create a new file', 'create_file --allow-fallback=shifted,ascii n create_file')
map('Create a new directory', 'create_dir shift+n create_dir')
map('Rename the selected entry', 'rename --allow-fallback=shifted,ascii r rename')
map(
'Delete the selected entry',
'delete --allow-fallback=shifted,ascii d delete',
long_text="""
Deletes a file, a symbolic link or an empty directory after asking for
confirmation. Directories are never deleted recursively.
""",
)
map('Copy the path of the selection to the clipboard', 'copy_path --allow-fallback=shifted,ascii y copy_path')
map('Reload the current directory', 'refresh --allow-fallback=shifted,ascii ctrl+r refresh')
egr()
OPTIONS = partial(
"""\
--start-dir
Directory to start browsing in. Defaults to the current working directory.
--show-hidden
type=bool-set
Show hidden files when the panel opens.
--config -c
type=list
completion=type:file ext:conf group:"Config files" kwds:none,NONE
{config_help}
--override -o
type=list
Override individual configuration options, can be specified multiple times.
Syntax: :italic:`name=value`. For example: :italic:`-o show_hidden=yes`
""".format,
config_help=CONFIG_HELP.format(conf_name='file-manager', appname=appname),
)
def main(args: list[str]) -> None:
raise SystemExit('This kitten must be run from a kitty.conf mapping')
def change_directory(w: Any, path: str) -> None:
# Writing to the pty, unlike pasting, makes the shell run the command. When
# the shell is busy, only paste the text so that it can be edited instead of
# feeding it into whatever program is running.
cmd = 'cd ' + shlex.quote(path)
if w.at_prompt:
w.write_to_child(cmd + '\r')
else:
w.paste_text(cmd)
def open_in_new_tab(boss: BossType, w: Any, path: str) -> None:
from kitty.tabs import SpecialWindow
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))
@result_handler(has_ready_notification=True)
def handle_result(args: list[str], data: dict[str, Any], target_window_id: int, boss: BossType) -> None:
if not data:
return
action, path = data.get('action'), data.get('path')
if not action or not path:
return
w = boss.window_id_map.get(target_window_id)
if w is None:
boss.ring_bell_if_allowed()
return
if action == 'cd':
change_directory(w, path)
elif action == 'open':
open_in_new_tab(boss, w, path)
help_text = 'Browse directories in a side panel and change the working directory of the shell without leaving it'
usage = '[directory]'
if __name__ == '__main__':
main(sys.argv)
elif __name__ == '__doc__':
cd = sys.cli_docs # type: ignore
cd['usage'] = usage
cd['options'] = OPTIONS
cd['help_text'] = help_text
cd['short_desc'] = 'Browse directories and change the shell directory'
cd['args_completion'] = CompletionSpec.from_string('type:directory')
elif __name__ == '__conf__':
sys.options_definition = definition # type: ignore
+171
View File
@@ -0,0 +1,171 @@
// License: GPLv3 Copyright: 2026, FWS
package file_manager
import (
"os"
"path/filepath"
"testing"
)
func TestSortEntriesDirectoriesFirstThenByName(t *testing.T) {
entries := []Entry{
{Name: "zebra.txt"},
{Name: "alpha.txt"},
{Name: "Beta.txt"},
{Name: "zdir", IsDir: true},
{Name: "adir", IsDir: true},
}
sort_entries(entries, "name")
expected := []string{"adir", "zdir", "alpha.txt", "Beta.txt", "zebra.txt"}
for i, name := range expected {
if entries[i].Name != name {
t.Fatalf("wrong order at %d: wanted %s got %s", i, name, entries[i].Name)
}
}
}
func TestSortEntriesByModificationTime(t *testing.T) {
entries := []Entry{
{Name: "old.txt", ModTime: 10},
{Name: "new.txt", ModTime: 30},
{Name: "mid.txt", ModTime: 20},
{Name: "dir", IsDir: true, ModTime: 1},
}
sort_entries(entries, "mtime")
expected := []string{"dir", "new.txt", "mid.txt", "old.txt"}
for i, name := range expected {
if entries[i].Name != name {
t.Fatalf("wrong order at %d: wanted %s got %s", i, name, entries[i].Name)
}
}
}
func TestReadDirSkipsHiddenFilesUnlessRequested(t *testing.T) {
dir := t.TempDir()
for _, name := range []string{"visible.txt", ".hidden.txt"} {
if err := os.WriteFile(filepath.Join(dir, name), nil, 0o644); err != nil {
t.Fatal(err)
}
}
if err := os.Mkdir(filepath.Join(dir, "sub"), 0o755); err != nil {
t.Fatal(err)
}
entries, err := read_dir(dir, false, "name")
if err != nil {
t.Fatal(err)
}
if len(entries) != 2 {
t.Fatalf("wanted 2 entries, got %d: %#v", len(entries), entries)
}
if !entries[0].IsDir || entries[0].Name != "sub" {
t.Fatalf("directories must be listed first, got %#v", entries[0])
}
entries, err = read_dir(dir, true, "name")
if err != nil {
t.Fatal(err)
}
if len(entries) != 3 {
t.Fatalf("wanted 3 entries with hidden files shown, got %d", len(entries))
}
}
func TestReadDirReportsErrors(t *testing.T) {
if _, err := read_dir(filepath.Join(t.TempDir(), "does-not-exist"), false, "name"); err == nil {
t.Fatal("reading a missing directory must fail")
}
}
func TestValidateEntryName(t *testing.T) {
for _, name := range []string{"", ".", "..", "a/b", "a\x00b"} {
if err := validate_entry_name(name); err == nil {
t.Fatalf("%q must be rejected", name)
}
}
for _, name := range []string{"file.txt", "with space", "..hidden"} {
if err := validate_entry_name(name); err != nil {
t.Fatalf("%q must be accepted, got %v", name, err)
}
}
}
func TestParentOf(t *testing.T) {
cases := map[string]string{
"/": "/",
"/tmp": "/",
"/tmp/a/b": "/tmp/a",
"/tmp/a/b/": "/tmp/a/b",
}
for input, expected := range cases {
if got := parent_of(input); got != expected {
t.Fatalf("parent_of(%q) = %q, wanted %q", input, got, expected)
}
}
}
func TestCreateRenameAndDelete(t *testing.T) {
dir := t.TempDir()
path, err := create_file(dir, "a.txt")
if err != nil {
t.Fatal(err)
}
if _, err = os.Stat(path); err != nil {
t.Fatal(err)
}
if _, err = create_file(dir, "a.txt"); err == nil {
t.Fatal("creating an existing file must fail")
}
if _, err = create_subdir(dir, "sub"); err != nil {
t.Fatal(err)
}
renamed, err := rename_entry(dir, "a.txt", "b.txt")
if err != nil {
t.Fatal(err)
}
if filepath.Base(renamed) != "b.txt" {
t.Fatalf("unexpected rename destination %q", renamed)
}
if _, err = os.Stat(filepath.Join(dir, "a.txt")); err == nil {
t.Fatal("the old name must no longer exist")
}
if _, err = rename_entry(dir, "b.txt", "sub"); err == nil {
t.Fatal("renaming over an existing entry must fail")
}
if err = delete_entry(dir, "b.txt"); err != nil {
t.Fatal(err)
}
if _, err = os.Stat(filepath.Join(dir, "b.txt")); err == nil {
t.Fatal("the deleted file must no longer exist")
}
if err = delete_entry(dir, ".."); err == nil {
t.Fatal("deleting the parent directory must be refused")
}
}
func TestResolveStartDirAcceptsFiles(t *testing.T) {
dir := t.TempDir()
file := filepath.Join(dir, "file.txt")
if err := os.WriteFile(file, nil, 0o644); err != nil {
t.Fatal(err)
}
got, err := resolve_start_dir(file)
if err != nil {
t.Fatal(err)
}
if got != dir {
t.Fatalf("starting from a file must use its directory, got %q wanted %q", got, dir)
}
}
func TestTruncateToWidth(t *testing.T) {
if got := truncate_to_width("abcdef", 3); got != "ab\u2026" {
t.Fatalf("unexpected truncation %q", got)
}
if got := truncate_to_width("abc", 10); got != "abc" {
t.Fatalf("short text must not be truncated, got %q", got)
}
}
+3
View File
@@ -14,6 +14,7 @@ import (
"github.com/kovidgoyal/kitty/kittens/desktop_ui"
"github.com/kovidgoyal/kitty/kittens/diff"
"github.com/kovidgoyal/kitty/kittens/dnd"
"github.com/kovidgoyal/kitty/kittens/file_manager"
"github.com/kovidgoyal/kitty/kittens/hints"
"github.com/kovidgoyal/kitty/kittens/hyperlinked_grep"
"github.com/kovidgoyal/kitty/kittens/icat"
@@ -59,6 +60,8 @@ func KittyToolEntryPoints(root *cli.Command) {
clipboard.EntryPoint(root)
// dnd
dnd.EntryPoint(root)
// file-manager
file_manager.EntryPoint(root)
// icat
icat.EntryPoint(root)
// ssh