Skip to content

Narrow the list of files in Dired

Emacs’ standard file manager (or directory editor) can read a regular expression to mark the matching files. This is the command dired-mark-files-regexp, which is bound to ‘% m’ by default. For example, ‘% m _denote’ will match all files that have the ‘denote’ keyword (Features of the file-naming scheme for searching or filtering).

Once the files are matched, the user has two options: (i) narrow the list to the matching items or (ii) exclude the matching items from the list.

For the former, we want to toggle the marks by typing ‘t’ (calls the command dired-toggle-marks by default) and then hit the letter ‘k’ (for dired-do-kill-lines). The remaining files are those that match the regexp that was provided earlier.

For the latter approach of filtering out the matching items, simply involves the use of the ‘k’ command (dired-do-kill-lines) to omit the marked files from the list.

These sequences can be combined to incrementally narrow the list. Note that dired-do-kill-lines does not delete files: it simply hides them from the current view.

Revert to the original listing with ‘g’ (revert-buffer).

For a convenient wrapper, consider this example:

emacs-lisp
(defvar prot-dired--limit-hist '()
  "Minibuffer history for `prot-dired-limit-regexp'.")

;;;###autoload
(defun prot-dired-limit-regexp (regexp omit)
  "Limit Dired to keep files matching REGEXP.

With optional OMIT argument as a prefix (\\[universal-argument]),
exclude files matching REGEXP.

Restore the buffer with \\<dired-mode-map>`\\[revert-buffer]'."
  (interactive
   (list
    (read-regexp
     (concat "Files "
             (when current-prefix-arg
               (propertize "NOT " 'face 'warning))
             "matching PATTERN: ")
     nil 'prot-dired--limit-hist)
    current-prefix-arg))
  (dired-mark-files-regexp regexp)
  (unless omit (dired-toggle-marks))
  (dired-do-kill-lines))