Selectively sorting directory by date in completion

André Marçais <[email protected]> Sun, 22 Mar 2026 00:45:56 +0100
Newsgroups gmane.comp.shells.zsh.user
Message-ID <[email protected]>
Hello,

I'm posting here to share some of my configuration hoping it may be
useful to others. Also, what I've done feels pretty hacky, so if anyone
has suggestions, I'm a taker. But first, I explain my problem.

The downloads folder/directory (`~/dl` in my case) often has lots of
stuff in it but in most cases only the most recently downloaded file is
relevant. So alphabetical sort when completing file names under `~/dl`
makes no sense. There is `zstyle ':completion:*' file-sort date` which
is understood by `_path_files` to sort all file name completion by date.
I, however, find this to be undesirable for most directories other than
`~/dl` and a few others since alphabetical sort is better for scanning
with one's eyes. The global setting is too broad.

So here is the solution I came up with: I redefined `_path_files` by
symlinking `~/.local/share/zsh/site-functions/_path_files_old` to
`/usr/share/zsh/functions/Completion/Unix/_path_files` and by creating
the file `~/.local/share/zsh/site-functions/_path_files` containing

    #autoload

    case $PREFIX in
    */)
        case ${${~PREFIX:-./}:a} in
            $HOME/dl) curcontext=downloads ;;
            $HOME/tmp) curcontext=downloads ;;
            /tmp) curcontext=downloads ;;
        esac
        ;;
    esac

    _path_files_old

and adding the line

    zstyle ':completion:downloads:*' file-sort date # see our _path_files

to my `.zshrc`.

Thus far it seems to work, tough I'm uncertain about a few things:
- I'm not really sure my use of `$curcontext` is correct.
- The symlink feels kinda wrong.
- I use `${~spec}` to do filename expansion, but that also does filename
  generation. I'm not sure that's desirable.

Hope this helps someone. And again, hope to get some feedback.

Cheers,

André