Emacs: Move File to Dir (Categorize Files) 📜
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 dir paths for `xah-move-file-to-dir' to move file to. Each key is string for prompt, each value is dir path. 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. URL `http://xahlee.info/emacs/emacs/move_file_to_dir.html'")
(defun xah-move-file-to-dir (TargetDir) "Move current file to a dir in choices in variable `xah-move-to-target-dirs'. If in `dired', move marked files or current file, and refresh dired buffer. If not in `dired', move current file. After done, open the TargetDir. URL `http://xahlee.info/emacs/emacs/move_file_to_dir.html' Created: 2023-03-09 Version: 2025-08-29" (interactive (list (file-name-as-directory (cdr (assoc (completing-read "move file to dir:" xah-move-to-target-dirs nil t) xah-move-to-target-dirs))))) (let ((xdireddir (if (eq major-mode 'dired-mode) default-directory nil)) (xfiles (cond ((eq major-mode 'dired-mode) (dired-get-marked-files)) (buffer-file-name (list buffer-file-name)) (t (user-error "Current buffer is not a file nor `dired'"))))) (mapc (lambda (x) (let ((xnewPath (concat (file-name-as-directory TargetDir) (file-name-nondirectory x)))) (rename-file x xnewPath) (let ((xbuf (get-file-buffer x))) (when xbuf (with-current-buffer xbuf (set-visited-file-name xnewPath :NO-QUERY :ALONG-WITH-FILE)))))) xfiles) (message " Files %s moved to %s" (mapconcat 'identity xfiles "\n") TargetDir) ;; (when (boundp 'xah-recently-closed-buffers) ;; (push (cons nil (concat TargetDir (file-name-nondirectory (car xfiles)))) xah-recently-closed-buffers)) ;; (if (eq major-mode 'dired-mode) ;; (dired-revert) ;; (if buffer-file-name ;; (let ((xbufname (buffer-name)) (xbfn buffer-file-name)) ;; (dired (file-name-directory xbfn)) ;; (kill-buffer xbufname)) ;; (progn))) (when xdireddir (dired-revert)) (dired TargetDir)))