Merge pull request 'feat(file-manager): fuzzy search, action palette and quick open' (#39) from feat/file-manager-search into main
Reviewed-on: #39
This commit is contained in:
6 files changed
+608
-63
No files matched your search
@@ -182,6 +182,10 @@ shell : valider un répertoire dans un dock ne peut donc pas faire de `cd`.
|
||||
| `→` / `L` | Entre dans le répertoire sélectionné sans toucher au shell |
|
||||
| `←` / `Retour arrière` / `H` | Remonte au répertoire parent |
|
||||
| `Ctrl+Entrée` / `C` | Déplace le shell vers le répertoire affiché, sans tenir compte de la sélection |
|
||||
| `/` | Filtre la liste par recherche floue ; `Entrée` ouvre la sélection, `Échap` efface la requête |
|
||||
| `:` | Ouvre la palette des actions, filtrable, `Entrée` exécute l'action |
|
||||
| `O` / `T` | Ouvre le fichier sélectionné dans un nouvel onglet / une nouvelle fenêtre |
|
||||
| `A` | Alias de `Maj+N` : crée un répertoire |
|
||||
| `↑` / `K`, `↓` / `J` | Déplace la sélection |
|
||||
| `Page préc.` / `Ctrl+B`, `Page suiv.` / `Ctrl+F` | Déplace la sélection d'une page |
|
||||
| `Début` / `G`, `Fin` / `Maj+G` | Première / dernière entrée |
|
||||
@@ -217,7 +221,7 @@ Les réglages vivent dans `~/.config/kitty/file-manager.conf` (même syntaxe que
|
||||
# Afficher les fichiers cachés à l'ouverture
|
||||
show_hidden yes
|
||||
|
||||
# name (défaut) ou mtime (plus récent d'abord)
|
||||
# name (défaut), mtime (plus récent d'abord) ou size (plus gros d'abord)
|
||||
sort_by mtime
|
||||
|
||||
# Remplacer un raccourci
|
||||
|
||||
@@ -242,6 +242,12 @@ Detailed list of changes
|
||||
that it stays usable in a dock. It also copies paths and creates, renames and
|
||||
deletes entries after a confirmation
|
||||
|
||||
- The :doc:`file manager <kittens/file-manager>` can now filter its listing
|
||||
with a fuzzy query (:kbd:`/`), list and run its actions from an in-panel
|
||||
palette (:kbd:`:`), and open the selected file in a new tab (:kbd:`O`) or a
|
||||
new OS window (:kbd:`T`). Entries can also be sorted by size with
|
||||
:code:`sort_by size`.
|
||||
|
||||
- :doc:`choose-files <kittens/choose-files>`: Fix concurrent custom preview
|
||||
commands occasionally receiving the path of a different file.
|
||||
|
||||
|
||||
@@ -72,9 +72,28 @@ Actions
|
||||
:kbd:`↑`. Pendant la saisie d'un nom, la tabulation est ignorée : elle ne
|
||||
peut pas faire partie d'un nom de fichier.
|
||||
|
||||
:kbd:`/`
|
||||
filtre la liste à mesure de la saisie, avec la même recherche floue que la
|
||||
palette de commandes. :kbd:`Entrée` ouvre la sélection, :kbd:`Échap`
|
||||
efface la requête et rétablit la liste complète. Un nom de répertoire suivi
|
||||
d'un :code:`/` ne filtre que les répertoires ; la requête est oubliée en
|
||||
changeant de répertoire.
|
||||
|
||||
:kbd:`:`
|
||||
ouvre la palette des actions. Elle liste chaque action avec sa description,
|
||||
se filtre comme la recherche, et :kbd:`Entrée` exécute l'action
|
||||
sélectionnée. La liste est la source unique utilisée par ce document :
|
||||
toutes les actions configurables y figurent.
|
||||
|
||||
:kbd:`O` et :kbd:`T`
|
||||
ouvrent le fichier sélectionné dans un nouvel onglet, respectivement une
|
||||
nouvelle fenêtre du système. Sur un répertoire, elles y entrent sans
|
||||
toucher au répertoire du shell.
|
||||
|
||||
: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.
|
||||
affiché. Le nom se saisit dans la ligne d'état. :kbd:`A` est un alias de
|
||||
:kbd:`Maj+N`, pour les claviers où la combinaison est peu pratique.
|
||||
|
||||
:kbd:`R`
|
||||
renomme l'entrée sélectionnée.
|
||||
@@ -115,11 +134,17 @@ 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`.
|
||||
:code:`rename`, :code:`delete`, :code:`copy_path`, :code:`refresh`,
|
||||
:code:`search`, :code:`palette`, :code:`open_tab` et :code:`open_window`.
|
||||
:code:`search`, :code:`palette`, :code:`open_tab` et :code:`open_window` sont
|
||||
les actions des raccourcis :kbd:`/`, :kbd:`:`, :kbd:`O` et :kbd:`T`.
|
||||
La palette :kbd:`:` liste ces actions avec leur description, ce qui évite de
|
||||
retourner à ce document pour retrouver un nom.
|
||||
|
||||
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).
|
||||
nom en ignorant la casse), ``mtime`` (tri par date de dernière modification) ou
|
||||
``size`` (tri par taille, du plus gros au plus petit).
|
||||
|
||||
L'éditeur n'est pas choisi par le panneau : le fichier est confié à kitty, qui
|
||||
utilise son option :opt:`editor` de :file:`kitty.conf`. Quand celle-ci vaut
|
||||
|
||||
+418
-58
@@ -14,6 +14,7 @@ import (
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/cli"
|
||||
"github.com/kovidgoyal/kitty/tools/config"
|
||||
"github.com/kovidgoyal/kitty/tools/fzf"
|
||||
"github.com/kovidgoyal/kitty/tools/tui"
|
||||
"github.com/kovidgoyal/kitty/tools/tui/loop"
|
||||
"github.com/kovidgoyal/kitty/tools/wcswidth"
|
||||
@@ -27,6 +28,7 @@ type Entry struct {
|
||||
Name string
|
||||
IsDir bool
|
||||
ModTime int64
|
||||
Size int64
|
||||
}
|
||||
|
||||
type input_purpose int
|
||||
@@ -36,6 +38,7 @@ const (
|
||||
input_create_file
|
||||
input_create_dir
|
||||
input_rename
|
||||
input_search
|
||||
)
|
||||
|
||||
// Pure helpers, kept free of terminal state so that they can be unit tested
|
||||
@@ -51,8 +54,15 @@ func sort_entries(entries []Entry, sort_by string) {
|
||||
if a.IsDir != b.IsDir {
|
||||
return a.IsDir
|
||||
}
|
||||
if sort_by == "mtime" && a.ModTime != b.ModTime {
|
||||
return a.ModTime > b.ModTime
|
||||
switch sort_by {
|
||||
case "mtime":
|
||||
if a.ModTime != b.ModTime {
|
||||
return a.ModTime > b.ModTime
|
||||
}
|
||||
case "size":
|
||||
if a.Size != b.Size {
|
||||
return a.Size > b.Size
|
||||
}
|
||||
}
|
||||
return strings.ToLower(a.Name) < strings.ToLower(b.Name)
|
||||
})
|
||||
@@ -72,6 +82,7 @@ func read_dir(dir string, show_hidden bool, sort_by string) ([]Entry, error) {
|
||||
e := Entry{Name: name, IsDir: item.IsDir()}
|
||||
if info, ierr := item.Info(); ierr == nil {
|
||||
e.ModTime = info.ModTime().Unix()
|
||||
e.Size = info.Size()
|
||||
}
|
||||
entries = append(entries, e)
|
||||
}
|
||||
@@ -191,14 +202,20 @@ type Handler struct {
|
||||
screen_size loop.ScreenSize
|
||||
conf *Config
|
||||
cwd string
|
||||
all_entries []Entry
|
||||
entries []Entry
|
||||
selected int
|
||||
scroll int
|
||||
show_hidden bool
|
||||
search_query string
|
||||
input_purpose input_purpose
|
||||
text_buffer string
|
||||
rename_source string
|
||||
confirm_name string
|
||||
palette_open bool
|
||||
palette_query string
|
||||
palette []action_info
|
||||
palette_selected int
|
||||
message string
|
||||
result_action string
|
||||
result_path string
|
||||
@@ -232,9 +249,15 @@ func (h *Handler) load(dir string) error {
|
||||
return err
|
||||
}
|
||||
h.cwd = dir
|
||||
h.all_entries = entries
|
||||
h.entries = entries
|
||||
if h.selected >= len(entries) {
|
||||
h.selected = max(0, len(entries)-1)
|
||||
if h.search_query != "" {
|
||||
if err = h.apply_search(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if h.selected >= len(h.entries) {
|
||||
h.selected = max(0, len(h.entries)-1)
|
||||
}
|
||||
if h.scroll > h.selected {
|
||||
h.scroll = h.selected
|
||||
@@ -277,6 +300,8 @@ func (h *Handler) reload() {
|
||||
}
|
||||
|
||||
func (h *Handler) change_dir(dir string) {
|
||||
// A filter belongs to the directory it was typed in, not to the next one.
|
||||
h.search_query, h.text_buffer, h.input_purpose = "", "", input_none
|
||||
if err := h.load(dir); err != nil {
|
||||
h.message = err.Error()
|
||||
h.draw_screen()
|
||||
@@ -398,6 +423,9 @@ func (h *Handler) copy_selected_path() {
|
||||
// activate implements the primary action: the selected directory becomes the
|
||||
// working directory of the shell, the selected file is opened in the editor.
|
||||
func (h *Handler) activate() {
|
||||
if h.input_purpose == input_search {
|
||||
h.stop_search()
|
||||
}
|
||||
e, ok := h.selected_entry()
|
||||
if !ok {
|
||||
h.lp.Beep()
|
||||
@@ -411,15 +439,24 @@ func (h *Handler) activate() {
|
||||
h.open_file(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.
|
||||
// edit_args_in is the client side of kitty's edit protocol. The terminal opens
|
||||
// the editor in a new tab or OS window, which gives the file a whole window even
|
||||
// when the panel is docked. The window 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_in(path, window_type string) []string {
|
||||
return []string{"edit-in-kitty", "--type=" + window_type, path}
|
||||
}
|
||||
|
||||
func edit_args(path string) []string {
|
||||
return []string{"edit-in-kitty", "--type=tab", path}
|
||||
return edit_args_in(path, "tab")
|
||||
}
|
||||
|
||||
func (h *Handler) open_file(path string) {
|
||||
h.open_file_in(path, "tab")
|
||||
}
|
||||
|
||||
func (h *Handler) open_file_in(path, window_type string) {
|
||||
exe, err := os.Executable()
|
||||
if err != nil {
|
||||
h.message = err.Error()
|
||||
@@ -429,7 +466,7 @@ func (h *Handler) open_file(path string) {
|
||||
// The loop must give up the tty while edit-in-kitty talks to the terminal,
|
||||
// otherwise both processes compete for input and escape code responses.
|
||||
err = h.lp.SuspendAndRun(func() error {
|
||||
cmd := exec.Command(exe, edit_args(path)...)
|
||||
cmd := exec.Command(exe, edit_args_in(path, window_type)...)
|
||||
cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr
|
||||
return cmd.Run()
|
||||
})
|
||||
@@ -473,53 +510,346 @@ func (h *Handler) change_shell_dir() {
|
||||
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":
|
||||
type action_info struct {
|
||||
Name string
|
||||
Description string
|
||||
}
|
||||
|
||||
// action_catalog is the single source of truth shared by the in-panel palette
|
||||
// and the documentation: every action accepted by perform_action has exactly
|
||||
// one description here, and test_action_catalog enforces that.
|
||||
var action_catalog = []action_info{
|
||||
{"quit", "Close the panel without changing the shell directory"},
|
||||
{"move_up", "Select the previous entry"},
|
||||
{"move_down", "Select the next entry"},
|
||||
{"page_up", "Move the selection up by one page"},
|
||||
{"page_down", "Move the selection down by one page"},
|
||||
{"home", "Select the first entry"},
|
||||
{"end", "Select the last entry"},
|
||||
{"activate", "Change the shell directory or open the selected file"},
|
||||
{"enter_dir", "Browse into the selected directory"},
|
||||
{"parent_dir", "Browse into the parent directory"},
|
||||
{"cd_here", "Move the shell to the directory shown in the panel"},
|
||||
{"toggle_hidden", "Show or hide entries whose name starts with a dot"},
|
||||
{"create_file", "Create a file in the current directory"},
|
||||
{"create_dir", "Create a directory in the current directory"},
|
||||
{"rename", "Rename the selected entry"},
|
||||
{"delete", "Delete the selected entry after confirmation"},
|
||||
{"copy_path", "Copy the path of the selection to the clipboard"},
|
||||
{"refresh", "Reload the current directory"},
|
||||
{"search", "Filter the listing with a fuzzy query"},
|
||||
{"palette", "List and run the actions of the panel"},
|
||||
{"open_tab", "Open the selected file in a new tab"},
|
||||
{"open_window", "Open the selected file in a new OS window"},
|
||||
}
|
||||
|
||||
// Actions that need the panel state are plain functions of the handler, so the
|
||||
// palette and the configurable shortcuts go through the same code path.
|
||||
var action_handlers = map[string]func(*Handler){
|
||||
"quit": func(h *Handler) { h.lp.Quit(0) },
|
||||
"move_up": func(h *Handler) { h.move_selection(-1) },
|
||||
"move_down": func(h *Handler) { h.move_selection(1) },
|
||||
"page_up": func(h *Handler) {
|
||||
h.move_selection(-max(1, int(h.screen_size.HeightCells)-3))
|
||||
case "page_down":
|
||||
},
|
||||
"page_down": func(h *Handler) {
|
||||
h.move_selection(max(1, int(h.screen_size.HeightCells)-3))
|
||||
case "home":
|
||||
},
|
||||
"home": func(h *Handler) {
|
||||
h.selected = 0
|
||||
h.draw_screen()
|
||||
case "end":
|
||||
},
|
||||
"end": func(h *Handler) {
|
||||
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":
|
||||
},
|
||||
"parent_dir": func(h *Handler) { h.change_dir(parent_of(h.cwd)) },
|
||||
"activate": func(h *Handler) { h.activate() },
|
||||
"enter_dir": func(h *Handler) { h.enter_dir() },
|
||||
"cd_here": func(h *Handler) { h.change_shell_dir() },
|
||||
"toggle_hidden": func(h *Handler) { h.show_hidden = !h.show_hidden; h.reload() },
|
||||
"create_file": func(h *Handler) { h.start_input(input_create_file) },
|
||||
"create_dir": func(h *Handler) { h.start_input(input_create_dir) },
|
||||
"rename": func(h *Handler) { h.start_rename() },
|
||||
"delete": func(h *Handler) { h.start_delete() },
|
||||
"copy_path": func(h *Handler) { h.copy_selected_path() },
|
||||
"refresh": func(h *Handler) { h.reload() },
|
||||
"search": func(h *Handler) { h.start_search() },
|
||||
"palette": func(h *Handler) { h.open_palette() },
|
||||
"open_tab": func(h *Handler) { h.open_selected("tab") },
|
||||
"open_window": func(h *Handler) { h.open_selected("window") },
|
||||
}
|
||||
|
||||
func (h *Handler) perform_action(name string) {
|
||||
if fn, ok := action_handlers[name]; ok {
|
||||
fn(h)
|
||||
}
|
||||
}
|
||||
|
||||
// filter_entries keeps the entries matching query, using the same fuzzy matcher
|
||||
// as the command palette so that scoring stays consistent across kittens. An
|
||||
// empty query keeps the listing untouched.
|
||||
func filter_entries(entries []Entry, query string) ([]Entry, error) {
|
||||
if query == "" {
|
||||
return entries, nil
|
||||
}
|
||||
names := make([]string, len(entries))
|
||||
for i, e := range entries {
|
||||
names[i] = e.Name
|
||||
if e.IsDir {
|
||||
// Matching the trailing slash lets a query such as "src/" only
|
||||
// select directories.
|
||||
names[i] += "/"
|
||||
}
|
||||
}
|
||||
m := fzf.NewFuzzyMatcher(fzf.PATH_SCHEME)
|
||||
results, err := m.Score(names, query)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
type scored_entry struct {
|
||||
entry Entry
|
||||
score uint
|
||||
}
|
||||
matches := make([]scored_entry, 0, len(entries))
|
||||
for i, r := range results {
|
||||
if r.Score > 0 {
|
||||
matches = append(matches, scored_entry{entries[i], r.Score})
|
||||
}
|
||||
}
|
||||
sort.SliceStable(matches, func(i, j int) bool {
|
||||
if matches[i].score != matches[j].score {
|
||||
return matches[i].score > matches[j].score
|
||||
}
|
||||
return strings.ToLower(matches[i].entry.Name) < strings.ToLower(matches[j].entry.Name)
|
||||
})
|
||||
ans := make([]Entry, len(matches))
|
||||
for i, m := range matches {
|
||||
ans[i] = m.entry
|
||||
}
|
||||
return ans, nil
|
||||
}
|
||||
|
||||
// filter_actions keeps the actions whose name or description matches query, most
|
||||
// relevant first. An empty query lists the whole catalog.
|
||||
func filter_actions(query string) ([]action_info, error) {
|
||||
if query == "" {
|
||||
return action_catalog, nil
|
||||
}
|
||||
texts := make([]string, len(action_catalog))
|
||||
for i, a := range action_catalog {
|
||||
texts[i] = a.Name + " " + a.Description
|
||||
}
|
||||
m := fzf.NewFuzzyMatcher(fzf.DEFAULT_SCHEME)
|
||||
results, err := m.Score(texts, query)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
type scored_action struct {
|
||||
action action_info
|
||||
score uint
|
||||
}
|
||||
matches := make([]scored_action, 0, len(action_catalog))
|
||||
for i, r := range results {
|
||||
if r.Score > 0 {
|
||||
matches = append(matches, scored_action{action_catalog[i], r.Score})
|
||||
}
|
||||
}
|
||||
sort.SliceStable(matches, func(i, j int) bool {
|
||||
if matches[i].score != matches[j].score {
|
||||
return matches[i].score > matches[j].score
|
||||
}
|
||||
return matches[i].action.Name < matches[j].action.Name
|
||||
})
|
||||
ans := make([]action_info, len(matches))
|
||||
for i, m := range matches {
|
||||
ans[i] = m.action
|
||||
}
|
||||
return ans, nil
|
||||
}
|
||||
|
||||
func (h *Handler) start_search() {
|
||||
h.input_purpose = input_search
|
||||
h.text_buffer, h.search_query = "", ""
|
||||
h.entries = h.all_entries
|
||||
h.selected, h.scroll, h.message = 0, 0, ""
|
||||
h.draw_screen()
|
||||
}
|
||||
|
||||
// apply_search filters the listing without redrawing, so that it can also be
|
||||
// used from load() while the panel is being rebuilt.
|
||||
func (h *Handler) apply_search() error {
|
||||
entries, err := filter_entries(h.all_entries, h.search_query)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
h.entries = entries
|
||||
h.selected = max(0, min(h.selected, len(h.entries)-1))
|
||||
h.scroll = 0
|
||||
return nil
|
||||
}
|
||||
|
||||
// stop_search clears the filter and restores the full listing, keeping the
|
||||
// selection on the entry the user was looking at when it still exists.
|
||||
func (h *Handler) stop_search() {
|
||||
name := ""
|
||||
if e, ok := h.selected_entry(); ok {
|
||||
name = e.Name
|
||||
}
|
||||
h.input_purpose, h.text_buffer, h.search_query = input_none, "", ""
|
||||
h.entries = h.all_entries
|
||||
h.selected, h.scroll = 0, 0
|
||||
h.select_name(name)
|
||||
if h.selected >= len(h.entries) {
|
||||
h.selected = max(0, len(h.entries)-1)
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Handler) handle_search_key(ev *loop.KeyEvent) error {
|
||||
switch {
|
||||
case ev.MatchesPressOrRepeat("escape"):
|
||||
ev.Handled = true
|
||||
h.stop_search()
|
||||
h.draw_screen()
|
||||
case ev.MatchesPressOrRepeat("enter"):
|
||||
ev.Handled = true
|
||||
h.activate()
|
||||
case "enter_dir":
|
||||
case ev.MatchesPressOrRepeat("up"):
|
||||
ev.Handled = true
|
||||
h.move_selection(-1)
|
||||
case ev.MatchesPressOrRepeat("down"):
|
||||
ev.Handled = true
|
||||
h.move_selection(1)
|
||||
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.search_query = h.text_buffer
|
||||
if err := h.apply_search(); err != nil {
|
||||
h.message = err.Error()
|
||||
}
|
||||
h.draw_screen()
|
||||
case ev.MatchesPressOrRepeat("tab"), ev.MatchesPressOrRepeat("shift+tab"):
|
||||
// Tabs cannot be part of a query here, they move the selection.
|
||||
ev.Handled = true
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *Handler) open_palette() {
|
||||
h.palette_open = true
|
||||
h.palette_query = ""
|
||||
h.palette = action_catalog
|
||||
h.palette_selected = 0
|
||||
h.message = ""
|
||||
h.draw_screen()
|
||||
}
|
||||
|
||||
func (h *Handler) close_palette() {
|
||||
h.palette_open = false
|
||||
h.palette_query = ""
|
||||
h.palette = nil
|
||||
h.palette_selected = 0
|
||||
h.draw_screen()
|
||||
}
|
||||
|
||||
func (h *Handler) update_palette() {
|
||||
actions, err := filter_actions(h.palette_query)
|
||||
if err != nil {
|
||||
h.message = err.Error()
|
||||
return
|
||||
}
|
||||
h.palette = actions
|
||||
h.palette_selected = max(0, min(h.palette_selected, len(h.palette)-1))
|
||||
}
|
||||
|
||||
func (h *Handler) run_palette_action() {
|
||||
if h.palette_selected < 0 || h.palette_selected >= len(h.palette) {
|
||||
h.close_palette()
|
||||
return
|
||||
}
|
||||
name := h.palette[h.palette_selected].Name
|
||||
h.palette_open, h.palette_query, h.palette = false, "", nil
|
||||
h.palette_selected = 0
|
||||
h.perform_action(name)
|
||||
}
|
||||
|
||||
func (h *Handler) handle_palette_key(ev *loop.KeyEvent) error {
|
||||
switch {
|
||||
case ev.MatchesPressOrRepeat("escape"):
|
||||
ev.Handled = true
|
||||
h.close_palette()
|
||||
case ev.MatchesPressOrRepeat("enter"):
|
||||
ev.Handled = true
|
||||
h.run_palette_action()
|
||||
case ev.MatchesPressOrRepeat("up"):
|
||||
ev.Handled = true
|
||||
h.palette_selected = max(0, h.palette_selected-1)
|
||||
h.draw_screen()
|
||||
case ev.MatchesPressOrRepeat("down"):
|
||||
ev.Handled = true
|
||||
h.palette_selected = min(max(0, len(h.palette)-1), h.palette_selected+1)
|
||||
h.draw_screen()
|
||||
case ev.MatchesPressOrRepeat("backspace"):
|
||||
ev.Handled = true
|
||||
if h.palette_query != "" {
|
||||
g := wcswidth.SplitIntoGraphemes(h.palette_query)
|
||||
h.palette_query = strings.Join(g[:len(g)-1], "")
|
||||
h.update_palette()
|
||||
h.draw_screen()
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// open_selected opens the selected file in the requested window type. The
|
||||
// window type is a launch type, so "tab" and "window" both work.
|
||||
func (h *Handler) open_selected(window_type string) {
|
||||
e, ok := h.selected_entry()
|
||||
if !ok {
|
||||
h.lp.Beep()
|
||||
return
|
||||
}
|
||||
if e.IsDir {
|
||||
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()
|
||||
return
|
||||
}
|
||||
h.open_file_in(entry_path(h.cwd, e.Name), window_type)
|
||||
}
|
||||
|
||||
func (h *Handler) draw_palette_list(width, list_start, list_height int) {
|
||||
if len(h.palette) == 0 {
|
||||
return
|
||||
}
|
||||
offset := 0
|
||||
if h.palette_selected >= list_height {
|
||||
offset = h.palette_selected - list_height + 1
|
||||
}
|
||||
for row := 0; row < list_height; row++ {
|
||||
idx := offset + row
|
||||
if idx >= len(h.palette) {
|
||||
break
|
||||
}
|
||||
a := h.palette[idx]
|
||||
text := truncate_to_width(fmt.Sprintf("%-18s %s", a.Name, a.Description), width-2)
|
||||
h.lp.MoveCursorTo(1, list_start+row)
|
||||
if idx == h.palette_selected {
|
||||
text += strings.Repeat(" ", max(0, width-wcswidth.Stringwidth(text)))
|
||||
h.lp.QueueWriteString(h.lp.SprintStyled("reverse", text))
|
||||
} else {
|
||||
h.lp.QueueWriteString(" " + text)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Handler) handle_input_key(ev *loop.KeyEvent) error {
|
||||
if h.input_purpose == input_search {
|
||||
return h.handle_search_key(ev)
|
||||
}
|
||||
switch {
|
||||
case ev.MatchesPressOrRepeat("escape"):
|
||||
ev.Handled = true
|
||||
@@ -558,6 +888,9 @@ func (h *Handler) on_key_event(ev *loop.KeyEvent) error {
|
||||
if h.input_purpose != input_none {
|
||||
return h.handle_input_key(ev)
|
||||
}
|
||||
if h.palette_open {
|
||||
return h.handle_palette_key(ev)
|
||||
}
|
||||
if h.confirm_name != "" {
|
||||
return h.handle_confirm_key(ev)
|
||||
}
|
||||
@@ -611,8 +944,20 @@ func (h *Handler) on_text(text string, from_key_event bool, in_bracketed_paste b
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if h.palette_open {
|
||||
h.palette_query += text
|
||||
h.update_palette()
|
||||
h.draw_screen()
|
||||
return nil
|
||||
}
|
||||
if h.input_purpose != input_none {
|
||||
h.text_buffer += text
|
||||
if h.input_purpose == input_search {
|
||||
h.search_query = h.text_buffer
|
||||
if err := h.apply_search(); err != nil {
|
||||
h.message = err.Error()
|
||||
}
|
||||
}
|
||||
h.draw_screen()
|
||||
}
|
||||
return nil
|
||||
@@ -680,6 +1025,8 @@ func (h *Handler) input_prompt() string {
|
||||
return "New directory:"
|
||||
case input_rename:
|
||||
return fmt.Sprintf("Rename %s to:", h.rename_source)
|
||||
case input_search:
|
||||
return "Search:"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -688,6 +1035,9 @@ func (h *Handler) status_text() string {
|
||||
if h.message != "" {
|
||||
return " " + truncate_to_width(h.message, max(1, int(h.screen_size.WidthCells)-1))
|
||||
}
|
||||
if h.search_query != "" {
|
||||
return fmt.Sprintf(" /%s %d matches", h.search_query, len(h.entries))
|
||||
}
|
||||
if len(h.entries) == 0 {
|
||||
return " Empty directory"
|
||||
}
|
||||
@@ -736,20 +1086,24 @@ func (h *Handler) draw_screen() {
|
||||
}
|
||||
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))
|
||||
if h.palette_open {
|
||||
h.draw_palette_list(width, list_start, list_height)
|
||||
} else {
|
||||
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))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -758,6 +1112,12 @@ func (h *Handler) draw_screen() {
|
||||
|
||||
h.lp.MoveCursorTo(1, height)
|
||||
switch {
|
||||
case h.palette_open:
|
||||
prompt := "Actions: "
|
||||
h.lp.SetCursorVisible(true)
|
||||
h.lp.QueueWriteString(h.lp.SprintStyled("fg=bright-yellow", prompt))
|
||||
h.lp.QueueWriteString(h.palette_query)
|
||||
h.lp.MoveCursorTo(1+wcswidth.Stringwidth(prompt+h.palette_query), height)
|
||||
case h.input_purpose != input_none:
|
||||
prompt := h.input_prompt() + " "
|
||||
h.lp.QueueWriteString(h.lp.SprintStyled("fg=bright-yellow", prompt))
|
||||
@@ -769,7 +1129,7 @@ func (h *Handler) draw_screen() {
|
||||
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"
|
||||
hints := "Enter: cd/open /: search :: actions ->: 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)))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -41,7 +41,8 @@ opt(
|
||||
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.
|
||||
sorted by last modification time, most recent first. :code:`size` lists
|
||||
directories first, then files sorted by size, largest first.
|
||||
""",
|
||||
)
|
||||
|
||||
@@ -127,6 +128,7 @@ map('Change shell directory to the directory being browsed', 'cd_here --allow-fa
|
||||
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('Create a new directory', 'create_dir --allow-fallback=shifted,ascii a create_dir')
|
||||
map('Rename the selected entry', 'rename --allow-fallback=shifted,ascii r rename')
|
||||
map(
|
||||
'Delete the selected entry',
|
||||
@@ -138,6 +140,26 @@ 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')
|
||||
map(
|
||||
'Filter the listing with a fuzzy query',
|
||||
'search --allow-fallback=shifted,ascii / search',
|
||||
long_text="""
|
||||
Filters the listing as text is typed, using the same fuzzy matcher as the
|
||||
command palette. :kbd:`Entrée` opens the selection, :kbd:`Échap` clears the
|
||||
query and restores the full listing.
|
||||
""",
|
||||
)
|
||||
map(
|
||||
'List and run the actions of the panel',
|
||||
'palette --allow-fallback=shifted,ascii : palette',
|
||||
long_text="""
|
||||
Lists every action of the panel with its description, filtered by a fuzzy query,
|
||||
and runs the selected one with :kbd:`Entrée`. The same actions can be bound to
|
||||
dedicated shortcuts in :file:`file-manager.conf`.
|
||||
""",
|
||||
)
|
||||
map('Open the selected file in a new tab', 'open_tab --allow-fallback=shifted,ascii o open_tab')
|
||||
map('Open the selected file in a new OS window', 'open_window --allow-fallback=shifted,ascii t open_window')
|
||||
|
||||
egr()
|
||||
|
||||
|
||||
@@ -3,9 +3,11 @@
|
||||
package file_manager
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestSortEntriesDirectoriesFirstThenByName(t *testing.T) {
|
||||
@@ -213,6 +215,132 @@ func TestResultPayload(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSortEntriesBySize(t *testing.T) {
|
||||
entries := []Entry{
|
||||
{Name: "small.txt", Size: 10},
|
||||
{Name: "large.txt", Size: 300},
|
||||
{Name: "medium.txt", Size: 20},
|
||||
{Name: "dir", IsDir: true, Size: 1},
|
||||
}
|
||||
sort_entries(entries, "size")
|
||||
expected := []string{"dir", "large.txt", "medium.txt", "small.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 TestFilterEntries(t *testing.T) {
|
||||
entries := []Entry{
|
||||
{Name: "alpha.txt"},
|
||||
{Name: "beta.txt"},
|
||||
{Name: "zeta.md"},
|
||||
{Name: "src", IsDir: true},
|
||||
}
|
||||
all, err := filter_entries(entries, "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(all) != len(entries) {
|
||||
t.Fatalf("an empty query must keep every entry, got %#v", all)
|
||||
}
|
||||
|
||||
matches, err := filter_entries(entries, "bt")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(matches) != 1 || matches[0].Name != "beta.txt" {
|
||||
t.Fatalf("unexpected matches for \"bt\": %#v", matches)
|
||||
}
|
||||
|
||||
dirs, err := filter_entries(entries, "src/")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(dirs) != 1 || !dirs[0].IsDir {
|
||||
t.Fatalf("a trailing slash must only match directories, got %#v", dirs)
|
||||
}
|
||||
|
||||
none, err := filter_entries(entries, "zzz")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(none) != 0 {
|
||||
t.Fatalf("a query that matches nothing must return nothing, got %#v", none)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFilterEntriesLargeDirectory(t *testing.T) {
|
||||
entries := make([]Entry, 10_000)
|
||||
for i := range entries {
|
||||
entries[i] = Entry{Name: fmt.Sprintf("file-%05d.txt", i)}
|
||||
}
|
||||
start := time.Now()
|
||||
matches, err := filter_entries(entries, "file-099")
|
||||
elapsed := time.Since(start)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(matches) == 0 {
|
||||
t.Fatal("expected matches in a large directory")
|
||||
}
|
||||
if elapsed > 100*time.Millisecond {
|
||||
t.Fatalf("filtering 10000 entries took %s, the limit is 100ms", elapsed)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFilterActions(t *testing.T) {
|
||||
all, err := filter_actions("")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(all) != len(action_catalog) {
|
||||
t.Fatalf("an empty query must list the whole catalog, got %d of %d", len(all), len(action_catalog))
|
||||
}
|
||||
matches, err := filter_actions("delete")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(matches) == 0 || matches[0].Name != "delete" {
|
||||
t.Fatalf("the palette must rank the delete action first, got %#v", matches)
|
||||
}
|
||||
}
|
||||
|
||||
func TestActionCatalogMatchesHandlers(t *testing.T) {
|
||||
seen := make(map[string]bool, len(action_catalog))
|
||||
for _, a := range action_catalog {
|
||||
if a.Name == "" || a.Description == "" {
|
||||
t.Fatalf("actions need a name and a description: %#v", a)
|
||||
}
|
||||
if seen[a.Name] {
|
||||
t.Fatalf("duplicate action %q in the catalog", a.Name)
|
||||
}
|
||||
seen[a.Name] = true
|
||||
if _, ok := action_handlers[a.Name]; !ok {
|
||||
t.Fatalf("action %q is described but has no handler", a.Name)
|
||||
}
|
||||
}
|
||||
for name := range action_handlers {
|
||||
if !seen[name] {
|
||||
t.Fatalf("action %q has a handler but no description in the palette", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestEditArgsInWindow(t *testing.T) {
|
||||
got := edit_args_in("/tmp/a.py", "window")
|
||||
want := []string{"edit-in-kitty", "--type=window", "/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 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