Emacs: Sort/Categorize Image Files to Dir (Move File to Dir) 🚀

By Xah Lee. Date: . Last updated: .

Here's a command that moves the current file (e.g. image file) to a choice dir. This is very useful when you have lots images, photos, screenshots, that you want to sort them out into different dirs such as food, travel, family, etc.

(defvar xah-move-to-target-dirs
    ("Documents" . "~/Documents/")
    ("Pictures" . "~/Pictures/")
    ("Desktop" . "~/Desktop/")
    ("Downloads" . "~/Downloads/")
  "An alist of dirs for `xah-move-file-to-dir' to move file to. Keys are strings, values are dir paths. Dir path must end in a slash. Useful is to create a bunch of dir, named family, travel, papers, work, etc, to sort photos into.")

(defun xah-move-file-to-dir ()
  "Move file (e.g. image) to a dir in `xah-move-to-target-dirs'.
If in `dired', move currnet file or marked files.

This command is for interactive use only.

URL `http://xahlee.info/emacs/emacs/move_file_to_dir.html'
Version 2023-03-09 2023-03-15 2023-03-18"
  (let (xname
         (file-name-as-directory (cdr (assoc (completing-read "pick a dir:" xah-move-to-target-dirs) xah-move-to-target-dirs))))
    (if (eq major-mode 'dired-mode)
        (let ((xfiles (dired-get-marked-files)))
           (lambda (xx)
             (setq xname (file-name-nondirectory xx))
             (setq xnewPath (format "%s%s" xtoDir xname))
             (rename-file xx xnewPath))
          (message "Files
moved to
                   (mapconcat 'identity xfiles "\n")
      (let ((xx buffer-file-name))
        (if xx
              (setq xname (file-name-nondirectory xx))
              (setq xnewPath (format "%s%s" xtoDir xname))
              (rename-file xx xnewPath)
              (message "File moved from \n%s\nto\n%s" xx xnewPath)
              (when (eq major-mode 'dired-mode) (revert-buffer)))
          (error "Current buffer is not a file. path value is 「%s」" xx))))))