Open a recent directory in dired: revisited

I wrote recently about how to use the command diredp-dired-recent-dirs from dired+ to open a recently used directory in dired. It turns out I had misunderstood what that command was for – it is intended to create a dired buffer containing a list of recently used directories, which is not exactly what I wanted.

Here is a function to give you a list of recent directories, using ivy (part of swiper) to narrow it dynamically, and then open the selected one in dired.

;; open recent directory, requires ivy (part of swiper)
;; borrows from
(defun bjm/ivy-dired-recent-dirs ()
  "Present a list of recently used directories and open the selected one in dired"
  (let ((recent-dirs
          (mapcar (lambda (file)
                    (if (file-directory-p file) file (file-name-directory file)))

    (let ((dir (ivy-read "Directory: "
                         :re-builder #'ivy--regex
                         :sort nil
                         :initial-input nil)))
      (dired dir))))

(global-set-key (kbd "C-x C-d") 'bjm/ivy-dired-recent-dirs)