2

When finding files with Ctrl-x Ctrl-f and then pressing Tab, to list the file completion names, is there a way to list these files in reverse order of their dates (when they were last edited)? Currently emacs lists them alphabetically. Is there a way of having the following two options: pressing Ctrl-x Ctrl-f Tab lists the files in alphabetical order, pressing Ctrl-x Ctrl-f space lists them in reverse order of dates?

Vikram
  • 327
  • 1
  • 7
  • 1
    The answer probably depends on the completion framework (i.e. default, ido, ivy, helm, ...) you are using. So you should share that info. – jue Feb 13 '20 at 14:43
  • 1
    sounds like default clean emacs since he uses tab. – RichieHH Feb 13 '20 at 15:22

2 Answers2

0

Vanilla Emacs doesn't let you choose the sort order in this context.

You can of course define your own command to use instead of what C-x C-f is bound to by default. But if you want to use read-file-name in that command then, again, you won't have much control over the order of candidates shown. If you instead use completing-read in the command, and you match file-name candidates only as strings, then you can order the set of candidates any way you like (and you can use relative or absolute file names). But in that case you lose the features of read-file-name (e.g. navigating up and down the file-system hierarchy).


If you use Icicles then you have multiple sort orders that you can switch among on the fly. See Icicles - File-Name Input and Icicles - Sorting Candidates for more info.

Drew
  • 77,472
  • 10
  • 114
  • 243
0

You can add the display sort function to the metadata of completion-file-name-table. The following lisp code shows how this can be done:

(defcustom file-name-completions-sort-function #'files-sort-access-time
  "Function for sorting the completion list of file names.
The function takes the list of file names as argument
and returns the sorted list."
  :type '(choice (function :tag "Sort Function") (const :tag "Natural Order" nil))
  :group 'files)

(defun files-sort-access-time (files) "Sort FILES list with respect to access time." (sort files (lambda (fn1 fn2) (time-less-p (file-attribute-access-time (file-attributes fn2)) (file-attribute-access-time (file-attributes fn1))))))

(defun ad-completion-file-name-table (fun string pred action) "Add 'display-sort-function' to metadata. If the completion action is metadata, add `file-name-completions-sort-function' as display-sort-function. Otherwise call FUN with STRING, PRED and ACTION as arguments." (if (and (functionp file-name-completions-sort-function) (eq action 'metadata)) (list 'metadata '(category . file) (cons 'display-sort-function file-name-completions-sort-function)) (funcall fun string pred action)))

(advice-add 'completion-file-name-table :around #'ad-completion-file-name-table)

Tobias
  • 33,167
  • 1
  • 37
  • 77