(eval-when-compile (require 'dired))
(defun dired-diff (file &optional switches)
"Compare file at point with file FILE using `diff'.
FILE defaults to the file at the mark.
The prompted-for file is the first file given to `diff'.
With prefix arg, prompt for second argument SWITCHES,
which is options for `diff'."
(interactive
(let ((default (if (mark t)
(save-excursion (goto-char (mark t))
(dired-get-filename t t)))))
(require 'diff)
(list (read-file-name (format "Diff %s with: %s"
(dired-get-filename t)
(if default
(concat "(default " default ") ")
""))
(dired-current-directory) default t)
(if current-prefix-arg
(read-string "Options for diff: "
(if (stringp diff-switches)
diff-switches
(mapconcat 'identity diff-switches " ")))))))
(diff file (dired-get-filename t) switches))
(defun dired-backup-diff (&optional switches)
"Diff this file with its backup file or vice versa.
Uses the latest backup, if there are several numerical backups.
If this file is a backup, diff it with its original.
The backup file is the first file given to `diff'.
With prefix arg, prompt for argument SWITCHES which is options for `diff'."
(interactive
(if current-prefix-arg
(list (read-string "Options for diff: "
(if (stringp diff-switches)
diff-switches
(mapconcat 'identity diff-switches " "))))
nil))
(diff-backup (dired-get-filename) switches))
(defun dired-do-chxxx (attribute-name program op-symbol arg)
(let* ((files (dired-get-marked-files t arg))
(new-attribute
(dired-mark-read-string
(concat "Change " attribute-name " of %s to: ")
nil op-symbol arg files))
(operation (concat program " " new-attribute))
failures)
(setq failures
(dired-bunch-files 10000
(function dired-check-process)
(append
(list operation program new-attribute)
(if (string-match "gnu" system-configuration)
'("--") nil))
files))
(dired-do-redisplay arg) (if failures
(dired-log-summary
(format "%s: error" operation)
nil))))
(defun dired-do-chmod (&optional arg)
"Change the mode of the marked (or next ARG) files.
This calls chmod, thus symbolic modes like `g+w' are allowed."
(interactive "P")
(dired-do-chxxx "Mode" dired-chmod-program 'chmod arg))
(defun dired-do-chgrp (&optional arg)
"Change the group of the marked (or next ARG) files."
(interactive "P")
(if (memq system-type '(ms-dos windows-nt))
(error "chgrp not supported on this system."))
(dired-do-chxxx "Group" "chgrp" 'chgrp arg))
(defun dired-do-chown (&optional arg)
"Change the owner of the marked (or next ARG) files."
(interactive "P")
(if (memq system-type '(ms-dos windows-nt))
(error "chown not supported on this system."))
(dired-do-chxxx "Owner" dired-chown-program 'chown arg))
(defun dired-bunch-files (max function args files)
(let (pending
(pending-length 0)
failures)
(while files
(let* ((thisfile (car files))
(thislength (+ (length thisfile) 3))
(rest (cdr files)))
(if (and pending (> (+ thislength pending-length) max))
(setq failures
(nconc (apply function (append args pending))
failures)
pending nil
pending-length 0))
(setcdr files pending)
(setq pending files)
(setq pending-length (+ thislength pending-length))
(setq files rest)))
(nconc (apply function (append args pending))
failures)))
(defun dired-do-print (&optional arg)
"Print the marked (or next ARG) files.
Uses the shell command coming from variables `lpr-command' and
`lpr-switches' as default."
(interactive "P")
(let* ((file-list (dired-get-marked-files t arg))
(command (dired-mark-read-string
"Print %s with: "
(mapconcat 'identity
(cons lpr-command
(if (stringp lpr-switches)
(list lpr-switches)
lpr-switches))
" ")
'print arg file-list)))
(dired-run-shell-command (dired-shell-stuff-it command file-list nil))))
(defun dired-mark-read-string (prompt initial op-symbol arg files)
(dired-mark-pop-up
nil op-symbol files
(function read-string)
(format prompt (dired-mark-prompt arg files)) initial))
(defvar dired-file-version-alist)
(defun dired-clean-directory (keep)
"Flag numerical backups for deletion.
Spares `dired-kept-versions' latest versions, and `kept-old-versions' oldest.
Positive prefix arg KEEP overrides `dired-kept-versions';
Negative prefix arg KEEP overrides `kept-old-versions' with KEEP made positive.
To clear the flags on these files, you can use \\[dired-flag-backup-files]
with a prefix argument."
(interactive "P")
(setq keep (if keep (prefix-numeric-value keep) dired-kept-versions))
(let ((early-retention (if (< keep 0) (- keep) kept-old-versions))
(late-retention (if (<= keep 0) dired-kept-versions keep))
(dired-file-version-alist ()))
(message "Cleaning numerical backups (keeping %d late, %d old)..."
late-retention early-retention)
(dired-map-dired-file-lines (function dired-collect-file-versions))
(let ((fval dired-file-version-alist))
(while fval
(let* ((sorted-v-list (cons 'q (sort (cdr (car fval)) '<)))
(v-count (length sorted-v-list)))
(if (> v-count (+ early-retention late-retention))
(rplacd (nthcdr early-retention sorted-v-list)
(nthcdr (- v-count late-retention)
sorted-v-list)))
(rplacd (car fval)
(cdr sorted-v-list)))
(setq fval (cdr fval))))
(dired-map-dired-file-lines (function dired-trample-file-versions))
(message "Cleaning numerical backups...done")))
(defun dired-map-dired-file-lines (fun)
(save-excursion
(let (file buffer-read-only)
(goto-char (point-min))
(while (not (eobp))
(save-excursion
(and (not (looking-at dired-re-dir))
(not (eolp))
(setq file (dired-get-filename nil t)) (progn (end-of-line)
(funcall fun file))))
(forward-line 1)))))
(defun dired-collect-file-versions (fn)
(let ((fn (file-name-sans-versions fn)))
(if (assoc fn dired-file-version-alist)
nil
(let* ((base-versions
(concat (file-name-nondirectory fn) ".~"))
(backup-extract-version-start (length base-versions))
(possibilities (file-name-all-completions
base-versions
(file-name-directory fn)))
(versions (mapcar 'backup-extract-version possibilities)))
(if versions
(setq dired-file-version-alist
(cons (cons fn versions)
dired-file-version-alist)))))))
(defun dired-trample-file-versions (fn)
(let* ((start-vn (string-match "\\.~[0-9]+~$" fn))
base-version-list)
(and start-vn
(setq base-version-list (assoc (substring fn 0 start-vn) dired-file-version-alist)) (not (memq (string-to-int (substring fn (+ 2 start-vn)))
base-version-list)) (progn (beginning-of-line)
(delete-char 1)
(insert dired-del-marker)))))
(defun dired-read-shell-command (prompt arg files)
(dired-mark-pop-up
nil 'shell files
(function read-string)
(format prompt (dired-mark-prompt arg files))
nil 'shell-command-history))
(defun dired-do-shell-command (command &optional arg file-list)
"Run a shell command COMMAND on the marked files.
If no files are marked or a specific numeric prefix arg is given,
the next ARG files are used. Just \\[universal-argument] means the current file.
The prompt mentions the file(s) or the marker, as appropriate.
If there is output, it goes to a separate buffer.
Normally the command is run on each file individually.
However, if there is a `*' in the command then it is run
just once with the entire file list substituted there.
No automatic redisplay of dired buffers is attempted, as there's no
telling what files the command may have changed. Type
\\[dired-do-redisplay] to redisplay the marked files.
The shell command has the top level directory as working directory, so
output files usually are created there instead of in a subdir."
(interactive
(let ((files (dired-get-marked-files t current-prefix-arg)))
(list
(dired-read-shell-command (concat "! on "
"%s: ")
current-prefix-arg
files)
current-prefix-arg
files)))
(let* ((on-each (not (string-match "\\*" command))))
(if on-each
(dired-bunch-files
(- 10000 (length command))
(function (lambda (&rest files)
(dired-run-shell-command
(dired-shell-stuff-it command files t arg))))
nil
file-list)
(dired-run-shell-command
(dired-shell-stuff-it command file-list nil arg)))))
(defvar dired-mark-prefix ""
"Prepended to marked files in dired shell commands.")
(defvar dired-mark-postfix ""
"Appended to marked files in dired shell commands.")
(defvar dired-mark-separator " "
"Separates marked files in dired shell commands.")
(defun dired-shell-stuff-it (command file-list on-each &optional raw-arg)
(let ((stuff-it
(if (string-match "\\*" command)
(function (lambda (x)
(dired-replace-in-string "\\*" x command)))
(function (lambda (x) (concat command " " x))))))
(if on-each
(mapconcat stuff-it (mapcar 'shell-quote-argument file-list) ";")
(let ((fns (mapconcat 'shell-quote-argument
file-list dired-mark-separator)))
(if (> (length file-list) 1)
(setq fns (concat dired-mark-prefix fns dired-mark-postfix)))
(funcall stuff-it fns)))))
(defun dired-run-shell-command (command)
(let ((handler
(find-file-name-handler (directory-file-name default-directory)
'shell-command)))
(if handler (apply handler 'shell-command (list command))
(shell-command command)))
nil)
(defun dired-call-process (program discard &rest arguments)
(let ((handler
(find-file-name-handler (directory-file-name default-directory)
'dired-call-process)))
(if handler (apply handler 'dired-call-process
program discard arguments)
(apply 'call-process program nil (not discard) nil arguments))))
(defun dired-check-process (msg program &rest arguments)
(let (err-buffer err (dir default-directory))
(message "%s..." msg)
(save-excursion
(setq err-buffer (get-buffer-create " *dired-check-process output*"))
(set-buffer err-buffer)
(erase-buffer)
(setq default-directory dir err (/= 0
(apply (function dired-call-process) program nil arguments)))
(if err
(progn
(dired-log (concat program " " (prin1-to-string arguments) "\n"))
(dired-log err-buffer)
(or arguments program t))
(kill-buffer err-buffer)
(message "%s...done" msg)
nil))))
(defun dired-kill-line (&optional arg)
(interactive "P")
(setq arg (prefix-numeric-value arg))
(let (buffer-read-only file)
(while (/= 0 arg)
(setq file (dired-get-filename nil t))
(if (not file)
(error "Can only kill file lines.")
(save-excursion (and file
(dired-goto-subdir file)
(dired-kill-subdir)))
(delete-region (progn (beginning-of-line) (point))
(progn (forward-line 1) (point)))
(if (> arg 0)
(setq arg (1- arg))
(setq arg (1+ arg))
(forward-line -1))))
(dired-move-to-filename)))
(defun dired-do-kill-lines (&optional arg fmt)
"Kill all marked lines (not the files).
With a prefix argument, kill that many lines starting with the current line.
\(A negative argument kills lines before the current line.)
To kill an entire subdirectory, go to its directory header line
and use this command with a prefix argument (the value does not matter)."
(interactive "P")
(if arg
(if (dired-get-subdir)
(dired-kill-subdir)
(dired-kill-line arg))
(save-excursion
(goto-char (point-min))
(let (buffer-read-only (count 0))
(if (not arg) (let ((regexp (dired-marker-regexp)))
(while (and (not (eobp))
(re-search-forward regexp nil t))
(setq count (1+ count))
(delete-region (progn (beginning-of-line) (point))
(progn (forward-line 1) (point)))))
(while (not (eobp))
(if (or (dired-between-files)
(not (looking-at "^ ")))
(forward-line 1)
(setq count (1+ count))
(delete-region (point) (save-excursion
(forward-line 1)
(point))))))
(or (equal "" fmt)
(message (or fmt "Killed %d line%s.") count (dired-plural-s count)))
count))))
(defun dired-compress ()
(let* (buffer-read-only
(from-file (dired-get-filename))
(new-file (dired-compress-file from-file)))
(if new-file
(let ((start (point)))
(condition-case nil
(dired-remove-entry new-file)
(error nil))
(goto-char start)
(dired-update-file-line new-file) nil)
(dired-log (concat "Failed to compress" from-file))
from-file)))
(defvar dired-compress-file-suffixes
'(("\\.gz\\'" "" "gunzip")
("\\.tgz\\'" ".tar" "gunzip")
("\\.Z\\'" "" "uncompress")
("\\.z\\'" "" "gunzip")
("\\.bz2\\'" "" "bunzip2")
("\\.tar\\'" ".tgz" nil))
"Control changes in file name suffixes for compression and uncompression.
Each element specifies one transformation rule, and has the form:
(REGEXP NEW-SUFFIX PROGRAM)
The rule applies when the old file name matches REGEXP.
The new file name is computed by deleting the part that matches REGEXP
(as well as anything after that), then adding NEW-SUFFIX in its place.
If PROGRAM is non-nil, the rule is an uncompression rule,
and uncompression is done by running PROGRAM.
Otherwise, the rule is a compression rule, and compression is done with gzip.")
(defun dired-compress-file (file)
(let ((handler (find-file-name-handler file 'dired-compress-file))
suffix newname
(suffixes dired-compress-file-suffixes))
(while suffixes
(let (case-fold-search)
(if (string-match (car (car suffixes)) file)
(setq suffix (car suffixes) suffixes nil))
(setq suffixes (cdr suffixes))))
(if suffix
(setq newname (concat (substring file 0 (match-beginning 0))
(nth 1 suffix))))
(cond (handler
(funcall handler 'dired-compress-file file))
((file-symlink-p file)
nil)
((and suffix (nth 2 suffix))
(if (not (dired-check-process (concat "Uncompressing " file)
(nth 2 suffix) file))
newname))
(t
(condition-case nil
(if (not (dired-check-process (concat "Compressing " file)
"gzip" "-f" file))
(let ((out-name
(if (file-exists-p (concat file ".gz"))
(concat file ".gz")
(concat file ".z"))))
(if (and newname (not (equal newname out-name)))
(progn
(rename-file out-name newname t)
newname)
out-name)))
(file-error
(if (not (dired-check-process (concat "Compressing " file)
"compress" "-f" file))
(concat file ".Z"))))))))
(defun dired-mark-confirm (op-symbol arg)
(or (eq dired-no-confirm t)
(memq op-symbol dired-no-confirm)
(let ((files (dired-get-marked-files t arg))
(string (if (eq op-symbol 'compress) "Compress or uncompress"
(capitalize (symbol-name op-symbol)))))
(dired-mark-pop-up nil op-symbol files (function y-or-n-p)
(concat string " "
(dired-mark-prompt arg files) "? ")))))
(defun dired-map-over-marks-check (fun arg op-symbol &optional show-progress)
(if (dired-mark-confirm op-symbol arg)
(let* ((total-list (dired-map-over-marks (funcall fun) arg show-progress))
(total (length total-list))
(failures (delq nil total-list))
(count (length failures))
(string (if (eq op-symbol 'compress) "Compress or uncompress"
(capitalize (symbol-name op-symbol)))))
(if (not failures)
(message "%s: %d file%s."
string total (dired-plural-s total))
(dired-log-summary
(format "Failed to %s %d of %d file%s"
(downcase string) count total (dired-plural-s total))
failures)))))
(defvar dired-query-alist
'((?\y . y) (?\040 . y) (?n . n) (?\177 . n) (?! . yes) (?q. no) (?\e . no) ))
(defun dired-query (qs-var qs-prompt &rest qs-args)
(let* ((char (symbol-value qs-var))
(action (cdr (assoc char dired-query-alist))))
(cond ((eq 'yes action)
t) ((eq 'no action)
nil) (t (let ((qprompt (concat qs-prompt
(if help-form
(format " [Type yn!q or %s] "
(key-description
(char-to-string help-char)))
" [Type y, n, q or !] ")))
result elt)
(apply 'message qprompt qs-args)
(setq char (set qs-var (read-char)))
(while (not (setq elt (assoc char dired-query-alist)))
(message "Invalid char - type %c for help." help-char)
(ding)
(sit-for 1)
(apply 'message qprompt qs-args)
(setq char (set qs-var (read-char))))
(memq (cdr elt) '(t y yes)))))))
(defun dired-do-compress (&optional arg)
"Compress or uncompress marked (or next ARG) files."
(interactive "P")
(dired-map-over-marks-check (function dired-compress) arg 'compress t))
(defun dired-byte-compile ()
(let* ((filename (dired-get-filename))
elc-file buffer-read-only failure)
(condition-case err
(save-excursion (byte-compile-file filename))
(error
(setq failure err)))
(setq elc-file (byte-compile-dest-file filename))
(or (file-exists-p elc-file)
(setq failure t))
(if failure
(progn
(dired-log "Byte compile error for %s:\n%s\n" filename failure)
(dired-make-relative filename))
(dired-remove-file elc-file)
(forward-line) (dired-add-file elc-file)
nil)))
(defun dired-do-byte-compile (&optional arg)
"Byte compile marked (or next ARG) Emacs Lisp files."
(interactive "P")
(dired-map-over-marks-check (function dired-byte-compile) arg 'byte-compile t))
(defun dired-load ()
(let ((file (dired-get-filename)) failure)
(condition-case err
(load file nil nil t)
(error (setq failure err)))
(if (not failure)
nil
(dired-log "Load error for %s:\n%s\n" file failure)
(dired-make-relative file))))
(defun dired-do-load (&optional arg)
"Load the marked (or next ARG) Emacs Lisp files."
(interactive "P")
(dired-map-over-marks-check (function dired-load) arg 'load t))
(defun dired-do-redisplay (&optional arg test-for-subdir)
"Redisplay all marked (or next ARG) files.
If on a subdir line, redisplay that subdirectory. In that case,
a prefix arg lets you edit the `ls' switches used for the new listing."
(interactive "P\np")
(if (and test-for-subdir (dired-get-subdir))
(dired-insert-subdir
(dired-get-subdir)
(if arg (read-string "Switches for listing: " dired-actual-switches)))
(message "Redisplaying...")
(dired-uncache
(if (consp dired-directory) (car dired-directory) dired-directory))
(dired-map-over-marks (let ((fname (dired-get-filename)))
(message "Redisplaying... %s" fname)
(dired-update-file-line fname))
arg)
(dired-move-to-filename)
(message "Redisplaying...done")))
(defun dired-update-file-line (file)
(beginning-of-line)
(let ((char (following-char)) (opoint (point))
(buffer-read-only))
(delete-region (point) (progn (forward-line 1) (point)))
(if file
(progn
(dired-add-entry file nil t)
(subst-char-in-region opoint (1+ opoint) ?\040 char))))
(dired-move-to-filename))
(defun dired-fun-in-all-buffers (directory file fun &rest args)
(let ((buf-list (dired-buffers-for-dir (expand-file-name directory)
file))
(obuf (current-buffer))
buf success-list)
(while buf-list
(setq buf (car buf-list)
buf-list (cdr buf-list))
(unwind-protect
(progn
(set-buffer buf)
(if (apply fun args)
(setq success-list (cons (buffer-name buf) success-list))))
(set-buffer obuf)))
success-list))
(defun dired-add-file (filename &optional marker-char)
(dired-fun-in-all-buffers
(file-name-directory filename) (file-name-nondirectory filename)
(function dired-add-entry) filename marker-char))
(defun dired-add-entry (filename &optional marker-char relative)
(setq filename (directory-file-name filename))
(let* ((opoint (point))
(cur-dir (dired-current-directory))
(orig-file-name filename)
(directory (if relative cur-dir (file-name-directory filename)))
reason)
(setq filename
(if relative
(file-relative-name filename directory)
(file-name-nondirectory filename))
reason
(catch 'not-found
(if (string= directory cur-dir)
(progn
(skip-chars-forward "^\r\n")
(if (eq (following-char) ?\r)
(dired-unhide-subdir))
(let ((p (dired-after-subdir-garbage cur-dir)))
(if (< (point) p)
(goto-char p))))
(if (dired-goto-subdir directory)
(progn (if (looking-at "\r") (dired-unhide-subdir))
(dired-goto-next-nontrivial-file))
(throw 'not-found "Subdir not found")))
(let (buffer-read-only opoint)
(beginning-of-line)
(setq opoint (point))
(dired-add-entry-do-indentation marker-char)
(let ((default-directory directory))
(insert-directory filename
(concat dired-actual-switches "d")))
(goto-char opoint)
(let ((inserted-name (dired-get-filename 'no-dir)))
(if (file-name-directory inserted-name)
(progn
(end-of-line)
(delete-char (- (length inserted-name)))
(insert filename)
(forward-char 1))
(forward-line 1)))
(dired-insert-set-properties opoint (point))
(forward-line -1)
(if dired-after-readin-hook (save-excursion (save-restriction
(beginning-of-line)
(narrow-to-region (point) (save-excursion
(forward-line 1) (point)))
(run-hooks 'dired-after-readin-hook))))
(dired-move-to-filename))
nil))
(if reason (goto-char opoint))
(not reason)))
(defun dired-add-entry-do-indentation (marker-char)
(insert (if marker-char
(if (integerp marker-char) marker-char dired-marker-char)
?\040)
?\040))
(defun dired-after-subdir-garbage (dir)
(save-excursion
(or (dired-goto-subdir dir) (error "This cannot happen"))
(forward-line 1)
(while (and (not (eolp)) (not (dired-move-to-filename)))
(forward-line 1))
(point)))
(defun dired-remove-file (file)
(dired-fun-in-all-buffers
(file-name-directory file) (file-name-nondirectory file)
(function dired-remove-entry) file))
(defun dired-remove-entry (file)
(save-excursion
(and (dired-goto-file file)
(let (buffer-read-only)
(delete-region (progn (beginning-of-line) (point))
(save-excursion (forward-line 1) (point)))))))
(defun dired-relist-file (file)
(dired-fun-in-all-buffers (file-name-directory file)
(file-name-nondirectory file)
(function dired-relist-entry) file))
(defun dired-relist-entry (file)
(let (buffer-read-only marker)
(save-excursion
(and (dired-goto-file file)
(delete-region (progn (beginning-of-line)
(setq marker (following-char))
(point))
(save-excursion (forward-line 1) (point))))
(setq file (directory-file-name file))
(dired-add-entry file (if (eq ?\040 marker) nil marker)))))
(defcustom dired-backup-overwrite nil
"*Non-nil if Dired should ask about making backups before overwriting files.
Special value `always' suppresses confirmation."
:type '(choice (const :tag "off" nil)
(const :tag "suppress" always)
(other :tag "ask" t))
:group 'dired)
(defvar dired-overwrite-confirmed)
(defun dired-handle-overwrite (to)
(let (backup)
(if (and dired-backup-overwrite
dired-overwrite-confirmed
(setq backup (car (find-backup-file-name to)))
(or (eq 'always dired-backup-overwrite)
(dired-query 'overwrite-backup-query
(format "Make backup for existing file `%s'? " to))))
(progn
(rename-file to backup 0) (dired-relist-entry backup)))))
(defun dired-copy-file (from to ok-flag)
(dired-handle-overwrite to)
(condition-case ()
(copy-file from to ok-flag dired-copy-preserve-time)
(file-date-error (message "Can't set date")
(sit-for 1))))
(defun dired-rename-file (from to ok-flag)
(dired-handle-overwrite to)
(rename-file from to ok-flag) (and (get-file-buffer from)
(with-current-buffer (get-file-buffer from)
(set-visited-file-name to nil t)))
(dired-remove-file from)
(dired-rename-subdir from to))
(defun dired-rename-subdir (from-dir to-dir)
(setq from-dir (file-name-as-directory from-dir)
to-dir (file-name-as-directory to-dir))
(dired-fun-in-all-buffers from-dir nil
(function dired-rename-subdir-1) from-dir to-dir)
(let ((expanded-from-dir (expand-file-name from-dir))
(blist (buffer-list)))
(while blist
(save-excursion
(set-buffer (car blist))
(if (and buffer-file-name
(dired-in-this-tree buffer-file-name expanded-from-dir))
(let ((modflag (buffer-modified-p))
(to-file (dired-replace-in-string
(concat "^" (regexp-quote from-dir))
to-dir
buffer-file-name)))
(set-visited-file-name to-file)
(set-buffer-modified-p modflag))))
(setq blist (cdr blist)))))
(defun dired-rename-subdir-1 (dir to)
(let ((expanded-dir (expand-file-name dir))
(alist dired-subdir-alist)
(elt nil))
(while alist
(setq elt (car alist)
alist (cdr alist))
(if (dired-in-this-tree (car elt) expanded-dir)
(dired-rename-subdir-2 elt dir to)))
(if (equal dir default-directory)
(progn
(dired-unadvertise dir) (setq default-directory to
dired-directory (expand-file-name (file-name-nondirectory dired-directory)
to))
(let ((new-name (file-name-nondirectory
(directory-file-name dired-directory))))
(or (get-buffer new-name)
(rename-buffer new-name)))
(dired-advertise)))))
(defun dired-rename-subdir-2 (elt dir to)
(save-excursion
(let ((regexp (regexp-quote (directory-file-name dir)))
(newtext (directory-file-name to))
buffer-read-only)
(goto-char (dired-get-subdir-min elt))
(if (not (looking-at dired-subdir-regexp))
(error "%s not found where expected - dired-subdir-alist broken?"
dir)
(goto-char (match-beginning 1))
(if (re-search-forward regexp (match-end 1) t)
(replace-match newtext t t)
(error "Expected to find `%s' in headerline of %s" dir (car elt))))
(setcar elt
(dired-normalize-subdir
(dired-replace-in-string regexp newtext (car elt)))))))
(defun dired-create-files (file-creator operation fn-list name-constructor
&optional marker-char)
(let (failures skipped (success-count 0) (total (length fn-list)))
(let (to overwrite-query
overwrite-backup-query) (mapcar
(function
(lambda (from)
(setq to (funcall name-constructor from))
(if (equal to from)
(progn
(setq to nil)
(dired-log "Cannot %s to same file: %s\n"
(downcase operation) from)))
(if (not to)
(setq skipped (cons (dired-make-relative from) skipped))
(let* ((overwrite (file-exists-p to))
(dired-overwrite-confirmed (and overwrite
(let ((help-form '(format "\
Type SPC or `y' to overwrite file `%s',
DEL or `n' to skip to next,
ESC or `q' to not overwrite any of the remaining files,
`!' to overwrite all remaining files with no more questions." to)))
(dired-query 'overwrite-query
"Overwrite `%s'?" to))))
(actual-marker-char
(cond ((integerp marker-char) marker-char)
(marker-char (dired-file-marker from)) (t nil))))
(condition-case err
(progn
(funcall file-creator from to dired-overwrite-confirmed)
(if overwrite
(dired-remove-file to))
(setq success-count (1+ success-count))
(message "%s: %d of %d" operation success-count total)
(dired-add-file to actual-marker-char))
(file-error (progn
(setq failures (cons (dired-make-relative from) failures))
(dired-log "%s `%s' to `%s' failed:\n%s\n"
operation from to err))))))))
fn-list))
(cond
(failures
(dired-log-summary
(format "%s failed for %d of %d file%s"
operation (length failures) total
(dired-plural-s total))
failures))
(skipped
(dired-log-summary
(format "%s: %d of %d file%s skipped"
operation (length skipped) total
(dired-plural-s total))
skipped))
(t
(message "%s: %s file%s"
operation success-count (dired-plural-s success-count)))))
(dired-move-to-filename))
(defun dired-do-create-files (op-symbol file-creator operation arg
&optional marker-char op1
how-to)
(or op1 (setq op1 operation))
(let* ((fn-list (dired-get-marked-files nil arg))
(fn-count (length fn-list))
(target (expand-file-name
(dired-mark-read-file-name
(concat (if (= 1 fn-count) op1 operation) " %s to: ")
(dired-dwim-target-directory)
op-symbol arg (mapcar (function dired-make-relative) fn-list))))
(into-dir (cond ((null how-to) (file-directory-p target))
((eq how-to t) nil)
(t (funcall how-to target)))))
(if (and (> fn-count 1)
(not into-dir))
(error "Marked %s: target must be a directory: %s" operation target))
(or into-dir (setq target (directory-file-name target)))
(dired-create-files
file-creator operation fn-list
(if into-dir (function (lambda (from)
(expand-file-name (file-name-nondirectory from) target)))
(function (lambda (from) target)))
marker-char)))
(defun dired-mark-read-file-name (prompt dir op-symbol arg files)
(dired-mark-pop-up
nil op-symbol files
(function read-file-name)
(format prompt (dired-mark-prompt arg files)) dir))
(defun dired-dwim-target-directory ()
(let ((this-dir (and (eq major-mode 'dired-mode)
(dired-current-directory))))
(if dired-dwim-target
(let* ((other-buf (window-buffer (next-window)))
(other-dir (save-excursion
(set-buffer other-buf)
(and (eq major-mode 'dired-mode)
(dired-current-directory)))))
(or other-dir this-dir))
this-dir)))
(defun dired-create-directory (directory)
"Create a directory called DIRECTORY."
(interactive
(list (read-file-name "Create directory: " (dired-current-directory))))
(let ((expanded (directory-file-name (expand-file-name directory))))
(make-directory expanded)
(dired-add-file expanded)
(dired-move-to-filename)))
(defun dired-into-dir-with-symlinks (target)
(and (file-directory-p target)
(not (file-symlink-p target))))
(defun dired-do-copy (&optional arg)
"Copy all marked (or next ARG) files, or copy the current file.
This normally preserves the last-modified date when copying.
When operating on just the current file, you specify the new name.
When operating on multiple or marked files, you specify a directory,
and new copies of these files are made in that directory
with the same names that the files currently have."
(interactive "P")
(dired-do-create-files 'copy (function dired-copy-file)
(if dired-copy-preserve-time "Copy [-p]" "Copy")
arg dired-keep-marker-copy))
(defun dired-do-symlink (&optional arg)
"Make symbolic links to current file or all marked (or next ARG) files.
When operating on just the current file, you specify the new name.
When operating on multiple or marked files, you specify a directory
and new symbolic links are made in that directory
with the same names that the files currently have."
(interactive "P")
(dired-do-create-files 'symlink (function make-symbolic-link)
"Symlink" arg dired-keep-marker-symlink))
(defun dired-do-hardlink (&optional arg)
"Add names (hard links) current file or all marked (or next ARG) files.
When operating on just the current file, you specify the new name.
When operating on multiple or marked files, you specify a directory
and new hard links are made in that directory
with the same names that the files currently have."
(interactive "P")
(dired-do-create-files 'hardlink (function add-name-to-file)
"Hardlink" arg dired-keep-marker-hardlink))
(defun dired-do-rename (&optional arg)
"Rename current file or all marked (or next ARG) files.
When renaming just the current file, you specify the new name.
When renaming multiple or marked files, you specify a directory."
(interactive "P")
(dired-do-create-files 'move (function dired-rename-file)
"Move" arg dired-keep-marker-rename "Rename"))
(defun dired-do-create-files-regexp
(file-creator operation arg regexp newname &optional whole-path marker-char)
(let* ((fn-list (dired-get-marked-files nil arg))
(fn-count (length fn-list))
(operation-prompt (concat operation " `%s' to `%s'?"))
(rename-regexp-help-form (format "\
Type SPC or `y' to %s one match, DEL or `n' to skip to next,
`!' to %s all remaining matches with no more questions."
(downcase operation)
(downcase operation)))
(regexp-name-constructor
(if whole-path (function
(lambda (from)
(let ((to (dired-string-replace-match regexp from newname))
(help-form rename-regexp-help-form))
(if to
(and (dired-query 'rename-regexp-query
operation-prompt
from
to)
to)
(dired-log "%s: %s did not match regexp %s\n"
operation from regexp)))))
(function
(lambda (from)
(let* ((new (dired-string-replace-match
regexp (file-name-nondirectory from) newname))
(to (and new (expand-file-name new
(file-name-directory from))))
(help-form rename-regexp-help-form))
(if to
(and (dired-query 'rename-regexp-query
operation-prompt
(dired-make-relative from)
(dired-make-relative to))
to)
(dired-log "%s: %s did not match regexp %s\n"
operation (file-name-nondirectory from) regexp)))))))
rename-regexp-query)
(dired-create-files
file-creator operation fn-list regexp-name-constructor marker-char)))
(defun dired-mark-read-regexp (operation)
(let* ((whole-path
(equal 0 (prefix-numeric-value current-prefix-arg)))
(arg
(if whole-path nil current-prefix-arg))
(regexp
(dired-read-regexp
(concat (if whole-path "Path " "") operation " from (regexp): ")))
(newname
(read-string
(concat (if whole-path "Path " "") operation " " regexp " to: "))))
(list regexp newname arg whole-path)))
(defun dired-do-rename-regexp (regexp newname &optional arg whole-path)
"Rename marked files containing REGEXP to NEWNAME.
As each match is found, the user must type a character saying
what to do with it. For directions, type \\[help-command] at that time.
NEWNAME may contain \\=\\<n> or \\& as in `query-replace-regexp'.
REGEXP defaults to the last regexp used.
With a zero prefix arg, renaming by regexp affects the absolute file name.
Normally, only the non-directory part of the file name is used and changed."
(interactive (dired-mark-read-regexp "Rename"))
(dired-do-create-files-regexp
(function dired-rename-file)
"Rename" arg regexp newname whole-path dired-keep-marker-rename))
(defun dired-do-copy-regexp (regexp newname &optional arg whole-path)
"Copy all marked files containing REGEXP to NEWNAME.
See function `dired-do-rename-regexp' for more info."
(interactive (dired-mark-read-regexp "Copy"))
(dired-do-create-files-regexp
(function dired-copy-file)
(if dired-copy-preserve-time "Copy [-p]" "Copy")
arg regexp newname whole-path dired-keep-marker-copy))
(defun dired-do-hardlink-regexp (regexp newname &optional arg whole-path)
"Hardlink all marked files containing REGEXP to NEWNAME.
See function `dired-do-rename-regexp' for more info."
(interactive (dired-mark-read-regexp "HardLink"))
(dired-do-create-files-regexp
(function add-name-to-file)
"HardLink" arg regexp newname whole-path dired-keep-marker-hardlink))
(defun dired-do-symlink-regexp (regexp newname &optional arg whole-path)
"Symlink all marked files containing REGEXP to NEWNAME.
See function `dired-do-rename-regexp' for more info."
(interactive (dired-mark-read-regexp "SymLink"))
(dired-do-create-files-regexp
(function make-symbolic-link)
"SymLink" arg regexp newname whole-path dired-keep-marker-symlink))
(defun dired-create-files-non-directory
(file-creator basename-constructor operation arg)
(let (rename-non-directory-query)
(dired-create-files
file-creator
operation
(dired-get-marked-files nil arg)
(function
(lambda (from)
(let ((to (concat (file-name-directory from)
(funcall basename-constructor
(file-name-nondirectory from)))))
(and (let ((help-form (format "\
Type SPC or `y' to %s one file, DEL or `n' to skip to next,
`!' to %s all remaining matches with no more questions."
(downcase operation)
(downcase operation))))
(dired-query 'rename-non-directory-query
(concat operation " `%s' to `%s'")
(dired-make-relative from)
(dired-make-relative to)))
to))))
dired-keep-marker-rename)))
(defun dired-rename-non-directory (basename-constructor operation arg)
(dired-create-files-non-directory
(function dired-rename-file)
basename-constructor operation arg))
(defun dired-upcase (&optional arg)
"Rename all marked (or next ARG) files to upper case."
(interactive "P")
(dired-rename-non-directory (function upcase) "Rename upcase" arg))
(defun dired-downcase (&optional arg)
"Rename all marked (or next ARG) files to lower case."
(interactive "P")
(dired-rename-non-directory (function downcase) "Rename downcase" arg))
(defun dired-maybe-insert-subdir (dirname &optional
switches no-error-if-not-dir-p)
"Insert this subdirectory into the same dired buffer.
If it is already present, just move to it (type \\[dired-do-redisplay] to refresh),
else inserts it at its natural place (as `ls -lR' would have done).
With a prefix arg, you may edit the ls switches used for this listing.
You can add `R' to the switches to expand the whole tree starting at
this subdirectory.
This function takes some pains to conform to `ls -lR' output."
(interactive
(list (dired-get-filename)
(if current-prefix-arg
(read-string "Switches for listing: " dired-actual-switches))))
(let ((opoint (point)))
(setq dirname (file-name-as-directory dirname))
(or (and (not switches)
(dired-goto-subdir dirname))
(dired-insert-subdir dirname switches no-error-if-not-dir-p))
(push-mark opoint)))
(defun dired-insert-subdir (dirname &optional switches no-error-if-not-dir-p)
"Insert this subdirectory into the same dired buffer.
If it is already present, overwrites previous entry,
else inserts it at its natural place (as `ls -lR' would have done).
With a prefix arg, you may edit the `ls' switches used for this listing.
You can add `R' to the switches to expand the whole tree starting at
this subdirectory.
This function takes some pains to conform to `ls -lR' output."
(interactive
(list (dired-get-filename)
(if current-prefix-arg
(read-string "Switches for listing: " dired-actual-switches))))
(setq dirname (file-name-as-directory (expand-file-name dirname)))
(dired-insert-subdir-validate dirname switches)
(or no-error-if-not-dir-p
(file-directory-p dirname)
(error "Attempt to insert a non-directory: %s" dirname))
(let ((elt (assoc dirname dired-subdir-alist))
switches-have-R mark-alist case-fold-search buffer-read-only)
(if (setq switches-have-R (and switches (string-match "R" switches)))
(setq mark-alist (dired-kill-tree dirname t)))
(if elt
(setq mark-alist (nconc (dired-insert-subdir-del elt) mark-alist))
(dired-insert-subdir-newpos dirname)) (dired-insert-subdir-doupdate
dirname elt (dired-insert-subdir-doinsert dirname switches))
(if switches-have-R (dired-build-subdir-alist))
(dired-initial-position dirname)
(save-excursion (dired-mark-remembered mark-alist))))
(defun dired-insert-subdir-validate (dirname &optional switches)
(or (dired-in-this-tree dirname (expand-file-name default-directory))
(error "%s: not in this directory tree" dirname))
(if switches
(let (case-fold-search)
(mapcar
(function
(lambda (x)
(or (eq (null (string-match x switches))
(null (string-match x dired-actual-switches)))
(error "Can't have dirs with and without -%s switches together"
x))))
'("F" "b")))))
(defun dired-alist-add (dir new-marker)
(dired-alist-add-1 dir new-marker)
(dired-alist-sort))
(defun dired-alist-sort ()
(setq dired-subdir-alist
(sort dired-subdir-alist
(function (lambda (elt1 elt2)
(> (dired-get-subdir-min elt1)
(dired-get-subdir-min elt2)))))))
(defun dired-kill-tree (dirname &optional remember-marks)
(interactive "DKill tree below directory: ")
(setq dirname (expand-file-name dirname))
(let ((s-alist dired-subdir-alist) dir m-alist)
(while s-alist
(setq dir (car (car s-alist))
s-alist (cdr s-alist))
(if (and (not (string-equal dir dirname))
(dired-in-this-tree dir dirname)
(dired-goto-subdir dir))
(setq m-alist (nconc (dired-kill-subdir remember-marks) m-alist))))
m-alist))
(defun dired-insert-subdir-newpos (new-dir)
(let ((alist dired-subdir-alist) elt dir pos new-pos)
(while alist
(setq elt (car alist)
alist (cdr alist)
dir (car elt)
pos (dired-get-subdir-min elt))
(if (dired-tree-lessp dir new-dir)
(setq new-pos (dired-get-subdir-max elt)
alist nil)))
(goto-char new-pos))
(or (eobp)
(forward-line -1))
(insert "\n")
(point))
(defun dired-insert-subdir-del (element)
(let ((begin-marker (dired-get-subdir-min element)))
(goto-char begin-marker)
(goto-char (dired-subdir-max))
(or (eobp) (forward-char -1))
(prog1
(dired-remember-marks begin-marker (point))
(delete-region begin-marker (point)))))
(defun dired-insert-subdir-doinsert (dirname switches)
(let ((begin (point)) end)
(message "Reading directory %s..." dirname)
(let ((dired-actual-switches
(or switches
(dired-replace-in-string "R" "" dired-actual-switches))))
(if (equal dirname (car (car (reverse dired-subdir-alist))))
(dired-readin-insert dired-directory)
(let ((opoint (point)))
(insert-directory dirname dired-actual-switches nil t)
(dired-insert-set-properties opoint (point)))))
(message "Reading directory %s...done" dirname)
(setq end (point-marker))
(indent-rigidly begin end 2)
(goto-char begin)
(if (not (looking-at "^ /.*:$"))
(dired-insert-headerline dirname))
(prog1
(list begin (marker-position end))
(set-marker end nil))))
(defun dired-insert-subdir-doupdate (dirname elt beg-end)
(if elt (set-marker (dired-get-subdir-min elt) (point-marker))
(dired-alist-add dirname (point-marker)))
(if dired-after-readin-hook
(save-excursion
(let ((begin (nth 0 beg-end))
(end (nth 1 beg-end)))
(goto-char begin)
(save-restriction
(narrow-to-region begin end)
(run-hooks 'dired-after-readin-hook))))))
(defun dired-tree-lessp (dir1 dir2)
(setq dir1 (file-name-as-directory dir1)
dir2 (file-name-as-directory dir2))
(let ((components-1 (dired-split "/" dir1))
(components-2 (dired-split "/" dir2)))
(while (and components-1
components-2
(equal (car components-1) (car components-2)))
(setq components-1 (cdr components-1)
components-2 (cdr components-2)))
(let ((c1 (car components-1))
(c2 (car components-2)))
(cond ((and c1 c2)
(string-lessp c1 c2))
((and (null c1) (null c2))
nil) ((null c1) t)
((null c2) nil)
(t (error "This can't happen"))))))
(defun dired-split (pat str &optional limit)
"Splitting on regexp PAT, turn string STR into a list of substrings.
Optional third arg LIMIT (>= 1) is a limit to the length of the
resulting list.
Thus, if SEP is a regexp that only matches itself,
(mapconcat 'identity (dired-split SEP STRING) SEP)
is always equal to STRING."
(let* ((start (string-match pat str))
(result (list (substring str 0 start)))
(count 1)
(end (if start (match-end 0))))
(if end (while (and (or (not (integerp limit))
(< count limit))
(string-match pat str end))
(setq start (match-beginning 0)
count (1+ count)
result (cons (substring str end start) result)
end (match-end 0)
start end)
))
(if (and (or (not (integerp limit))
(< count limit))
end) (setq result
(cons (substring str end) result)))
(nreverse result)))
(defun dired-prev-subdir (arg &optional no-error-if-not-found no-skip)
"Go to previous subdirectory, regardless of level.
When called interactively and not on a subdir line, go to this subdir's line."
(interactive
(list (if current-prefix-arg
(prefix-numeric-value current-prefix-arg)
(if (dired-get-subdir) 1 0))))
(dired-next-subdir (- arg) no-error-if-not-found no-skip))
(defun dired-subdir-min ()
(save-excursion
(if (not (dired-prev-subdir 0 t t))
(error "Not in a subdir!")
(point))))
(defun dired-goto-subdir (dir)
"Go to end of header line of DIR in this dired buffer.
Return value of point on success, otherwise return nil.
The next char is either \\n, or \\r if DIR is hidden."
(interactive
(prog1 (list (expand-file-name
(completing-read "Goto in situ directory: " dired-subdir-alist nil t (dired-current-directory))))
(push-mark)))
(setq dir (file-name-as-directory dir))
(let ((elt (assoc dir dired-subdir-alist)))
(and elt
(goto-char (dired-get-subdir-min elt))
(progn (skip-chars-forward "^\r\n")
(point)))))
(defun dired-mark-subdir-files ()
"Mark all files except `.' and `..' in current subdirectory.
If the Dired buffer shows multiple directories, this command
marks the files listed in the subdirectory that point is in."
(interactive)
(let ((p-min (dired-subdir-min)))
(dired-mark-files-in-region p-min (dired-subdir-max))))
(defun dired-kill-subdir (&optional remember-marks)
"Remove all lines of current subdirectory.
Lower levels are unaffected."
(interactive)
(let ((beg (dired-subdir-min))
(end (dired-subdir-max))
buffer-read-only cur-dir)
(setq cur-dir (dired-current-directory))
(if (equal cur-dir default-directory)
(error "Attempt to kill top level directory"))
(prog1
(if remember-marks (dired-remember-marks beg end))
(delete-region beg end)
(if (eobp) (delete-char -1))
(dired-unsubdir cur-dir))))
(defun dired-unsubdir (dir)
(setq dired-subdir-alist
(delq (assoc dir dired-subdir-alist) dired-subdir-alist)))
(defun dired-tree-up (arg)
"Go up ARG levels in the dired tree."
(interactive "p")
(let ((dir (dired-current-directory)))
(while (>= arg 1)
(setq arg (1- arg)
dir (file-name-directory (directory-file-name dir))))
(or (dired-goto-subdir dir)
(error "Cannot go up to %s - not in this tree." dir))))
(defun dired-tree-down ()
"Go down in the dired tree."
(interactive)
(let ((dir (dired-current-directory)) pos case-fold-search) (let ((rest (reverse dired-subdir-alist)) elt)
(while rest
(setq elt (car rest)
rest (cdr rest))
(if (dired-in-this-tree (directory-file-name (car elt)) dir)
(setq rest nil
pos (dired-goto-subdir (car elt))))))
(if pos
(goto-char pos)
(error "At the bottom"))))
(defun dired-unhide-subdir ()
(let (buffer-read-only)
(subst-char-in-region (dired-subdir-min) (dired-subdir-max) ?\r ?\n)))
(defun dired-hide-check ()
(or selective-display
(error "selective-display must be t for subdir hiding to work!")))
(defun dired-subdir-hidden-p (dir)
(and selective-display
(save-excursion
(dired-goto-subdir dir)
(looking-at "\r"))))
(defun dired-hide-subdir (arg)
"Hide or unhide the current subdirectory and move to next directory.
Optional prefix arg is a repeat factor.
Use \\[dired-hide-all] to (un)hide all directories."
(interactive "p")
(dired-hide-check)
(while (>= (setq arg (1- arg)) 0)
(let* ((cur-dir (dired-current-directory))
(hidden-p (dired-subdir-hidden-p cur-dir))
(elt (assoc cur-dir dired-subdir-alist))
(end-pos (1- (dired-get-subdir-max elt)))
buffer-read-only)
(goto-char (dired-get-subdir-min elt))
(skip-chars-forward "^\n\r")
(if hidden-p
(subst-char-in-region (point) end-pos ?\r ?\n)
(subst-char-in-region (point) end-pos ?\n ?\r)))
(dired-next-subdir 1 t)))
(defun dired-hide-all (arg)
"Hide all subdirectories, leaving only their header lines.
If there is already something hidden, make everything visible again.
Use \\[dired-hide-subdir] to (un)hide a particular subdirectory."
(interactive "P")
(dired-hide-check)
(let (buffer-read-only)
(if (save-excursion
(goto-char (point-min))
(search-forward "\r" nil t))
(subst-char-in-region (point-min) (point-max) ?\r ?\n)
(let ((pos (point-max)) (alist dired-subdir-alist))
(while alist (subst-char-in-region (dired-get-subdir-min (car alist)) (save-excursion
(goto-char pos) (forward-line -1)
(point))
?\n ?\r)
(setq pos (dired-get-subdir-min (car alist))) (setq alist (cdr alist)))))))
(defun dired-do-search (regexp)
"Search through all marked files for a match for REGEXP.
Stops when a match is found.
To continue searching for next match, use command \\[tags-loop-continue]."
(interactive "sSearch marked files (regexp): ")
(tags-search regexp '(dired-get-marked-files)))
(defun dired-do-query-replace (from to &optional delimited)
"Do `query-replace-regexp' of FROM with TO, on all marked files.
Third arg DELIMITED (prefix arg) means replace only word-delimited matches.
If you exit (\\[keyboard-quit] or ESC), you can resume the query replace
with the command \\[tags-loop-continue]."
(interactive
"sQuery replace in marked files (regexp): \nsQuery replace %s by: \nP")
(tags-query-replace from to delimited '(dired-get-marked-files)))
(provide 'dired-aux)