Emacs - sort directory / file list by modified date

The function (directory-files-and-attributes "~/" 'full nil t)

creates an unsorted list of files and directories for the home directory. The result is presented in a similar format, the file-attributes

documentation for which can be viewed at the following link: https://www.gnu.org/software/emacs/manual/html_node/elisp/File-Attributes.html

The purpose of this thread is to create a list that is sorted by modification date / time - with the newest at the top of the list and the oldest at the end of the list.

Finally, I would like to turn this verbose list into a simple list of only absolute file / directory paths - maintaining the same order that was achieved in the above sort.

+3


source to share


1 answer


directory-files-and-attributes

returns a list. Fortunately, there are many Lisp functions for converting lists.

First, you want to get a list sorted by comparing the 6th element of each record. You can do this using the built-in Emacs Lisp function sort

, which performs the comparison function as the second element:

(sort (directory-files-and-attributes "~")
      #'(lambda (x y) (time-less-p (nth 6 x) (nth 6 y))))

      

The same can be achieved, perhaps more clearly, using the Common Lisp collation function:



(cl-sort (directory-files-and-attributes "~")
         #'time-less-p
         :key #'(lambda (x) (nth 6 x)))

      

Now you only want to retrieve the first element of each entry - use mapcar

to apply the function to all elements of the list:

(mapcar #'car
        (sort (directory-files-and-attributes "~")
              #'(lambda (x y) (time-less-p (nth 6 x) (nth 6 y)))))

      

+5


source







All Articles