Zsh: make single file selection smart, stylish, and functionally correct (highlights, completions below cursor, etc)
0
votes
0
answers
204
views
I would like to have a near-flawless "single file selector" with zsh. So far I haven't seen one in questions as they tend to focus on zle settings for one's command line. Let's say we are writing a single file selector that prompts user to provide a single file in some directory. Below is my beginning code that works but needs multiple improvements:
1. Highlight: current menu selection item should be highlighted with reverse-video.
2. Order: the possible file completions should be shown below the prompt.
3. Prompt stepping: Prompt shouldn't step below after printing possible options above. This is related to 2.
4. Only one: Tab complete only first item, as we are asking for only 1 file name from user, not multiple. (This is what I mean by "functionally correct")
5. Size: If there are more possible completions than can fit below the prompt, that case is handled elegantly. Assume alternate screen, and no screen movement or scrolling available.
6. Bonus: If you could think of yet another nice feature to have for a single file selector, feel free to add. Though it would be nice to have it in a separate listing or with comments to identify how to remove your that from solution for 1-5 above.
Note: The answer would be self-contained zsh code. It wouldn't ask user to edit .zshrc or install some zsh extension/plugin/framework/library.
Create a file `
This is close ([zim](https://github.com/zimfw/zimfw) 's file completion):
foofiles.zsh
` in a temp directory, chmod and run it:
#!/usr/bin/env zsh
setopt extendedglob
setopt globcomplete
setopt nomenucomplete
mkdir ./foo 2>/dev/null
cd ./foo
touch abcd ebcf gbch ijkl mnop qrst unov wxyz
cd ..
function foofileselector {
cd ./foo/
local curcontext=foofileselector:::
vared -p "Select file: " -c foofile;
cd ..
}
function _foofileselector {
_files -W ./foo/
}
zstyle ':completion:foofileselector:*:' insert-tab false completer _foofileselector
autoload -Uz compinit && compinit
foofileselector
[[ -z $foofile ]] && foofile="NIL"
echo "You selected: $foofile"
rm -rf ./foo/
This is how it looks like:


Asked by codepoet
(626 rep)
Feb 10, 2023, 07:20 AM
Last activity: Feb 10, 2023, 07:36 AM
Last activity: Feb 10, 2023, 07:36 AM