Skip to content

Instantly share code, notes, and snippets.

@pkkm
Created April 24, 2013 19:35
Show Gist options
  • Save pkkm/5454899 to your computer and use it in GitHub Desktop.
Save pkkm/5454899 to your computer and use it in GitHub Desktop.
Sort Ido's file list by modification time.
;;; Utilities for file modification time.
(require 'cl)
(defun file-modtime (file)
"Get the last modification time of FILE.
If FILE cannot be read, return nil."
(let ((attributes (file-attributes file)))
(if attributes
(cl-sixth attributes)
nil)))
(defun file-modified-later-p (file-a file-b)
"Return t if FILE-A was modified later than FILE-B.
If FILE-B cannot be read, return t. If FILE-A cannot be read, nil."
(let ((modtime-a (file-modtime file-a))
(modtime-b (file-modtime file-b)))
(cond
((not modtime-b) t)
((not modtime-a) nil)
(t (time-less-p modtime-b modtime-a)))))
;;; Sort Ido's file list by modification time.
(require 'tramp)
(defun ido-sort-by-mtime ()
"Sort the Ido file list by modification time (most recent first).
Sort files handled by TRAMP alphabetically and display them after local files."
(setq ido-temp-list
(sort ido-temp-list
(lambda (a b)
(message ido-current-directory)
(cond
;; TRAMP files: don't check mtime, display at the end (after local files).
;; This will leave them sorted alphabetically (because ido-temp-list is sorted to start with).
;; `concat` instead of `expand-file-name`, because the latter will try to access the file.
((string-match tramp-file-name-regexp (concat ido-current-directory a)) nil)
((string-match tramp-file-name-regexp (concat ido-current-directory b)) t)
;; Local files: display the most recently modified first.
(t (file-modified-later-p
(expand-file-name a ido-current-directory)
(expand-file-name b ido-current-directory))))))))
(add-hook 'ido-make-file-list-hook 'ido-sort-by-mtime)
(add-hook 'ido-make-dir-list-hook 'ido-sort-by-mtime)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment