(eval-when-compile (require 'dired))
(defvar dired-create-files-failures nil
"Variable where `dired-create-files' records failing file names.
Functions that operate recursively can store additional names
into this list; they also should call `dired-log' to log the errors.")
(defconst dired-star-subst-regexp "\\(^\\|[ \t]\\)\\*\\([ \t]\\|$\\)")
(defconst dired-quark-subst-regexp "\\(^\\|[ \t]\\)\\?\\([ \t]\\|$\\)")
(defun dired-diff (file &optional switches)
"Compare file at point with file FILE using `diff'.
FILE defaults to the file at the mark. (That's the mark set by
\\[set-mark-command], not by Dired's \\[dired-mark] command.)
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 ((current (dired-get-filename t))
(default (if (mark t)
(save-excursion (goto-char (mark t))
(dired-get-filename t t)))))
(if (or (equal default current)
(and (not (equal (dired-dwim-target-directory)
(dired-current-directory)))
(not mark-active)))
(setq default nil))
(require 'diff)
(list (read-file-name (format "Diff %s with%s: "
current
(if default
(concat " (default " default ")")
""))
(if default
(dired-current-directory)
(dired-dwim-target-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-compare-directories (dir2 predicate)
"Mark files with different file attributes in two dired buffers.
Compare file attributes of files in the current directory
with file attributes in directory DIR2 using PREDICATE on pairs of files
with the same name. Mark files for which PREDICATE returns non-nil.
Mark files with different names if PREDICATE is nil (or interactively
with empty input at the predicate prompt).
PREDICATE is a Lisp expression that can refer to the following variables:
size1, size2 - file size in bytes
mtime1, mtime2 - last modification time in seconds, as a float
fa1, fa2 - list of file attributes
returned by function `file-attributes'
where 1 refers to attribute of file in the current dired buffer
and 2 to attribute of file in second dired buffer.
Examples of PREDICATE:
(> mtime1 mtime2) - mark newer files
(not (= size1 size2)) - mark files with different sizes
(not (string= (nth 8 fa1) (nth 8 fa2))) - mark files with different modes
(not (and (= (nth 2 fa1) (nth 2 fa2)) - mark files with different UID
(= (nth 3 fa1) (nth 3 fa2)))) and GID."
(interactive
(list (read-directory-name (format "Compare %s with: "
(dired-current-directory))
(dired-dwim-target-directory)
(dired-dwim-target-directory))
(read-from-minibuffer "Mark if (lisp expr or RET): " nil nil t nil "nil")))
(let* ((dir1 (dired-current-directory))
(file-alist1 (dired-files-attributes dir1))
(file-alist2 (dired-files-attributes dir2))
file-list1 file-list2)
(setq file-alist1 (delq (assoc "." file-alist1) file-alist1))
(setq file-alist1 (delq (assoc ".." file-alist1) file-alist1))
(setq file-alist2 (delq (assoc "." file-alist2) file-alist2))
(setq file-alist2 (delq (assoc ".." file-alist2) file-alist2))
(setq file-list1 (mapcar
'cadr
(dired-file-set-difference
file-alist1 file-alist2
predicate))
file-list2 (mapcar
'cadr
(dired-file-set-difference
file-alist2 file-alist1
predicate)))
(dired-fun-in-all-buffers
dir1 nil
(lambda ()
(dired-mark-if
(member (dired-get-filename nil t) file-list1) nil)))
(dired-fun-in-all-buffers
dir2 nil
(lambda ()
(dired-mark-if
(member (dired-get-filename nil t) file-list2) nil)))
(message "Marked in dir1: %s files, in dir2: %s files"
(length file-list1)
(length file-list2))))
(defun dired-file-set-difference (list1 list2 predicate)
"Combine LIST1 and LIST2 using a set-difference operation.
The result list contains all file items that appear in LIST1 but not LIST2.
This is a non-destructive function; it makes a copy of the data if necessary
to avoid corrupting the original LIST1 and LIST2.
PREDICATE (see `dired-compare-directories') is an additional match
condition. Two file items are considered to match if they are equal
*and* PREDICATE evaluates to t."
(if (or (null list1) (null list2))
list1
(let (res)
(dolist (file1 list1)
(unless (let ((list list2))
(while (and list
(not (let* ((file2 (car list))
(fa1 (car (cddr file1)))
(fa2 (car (cddr file2)))
(size1 (nth 7 fa1))
(size2 (nth 7 fa2))
(mtime1 (float-time (nth 5 fa1)))
(mtime2 (float-time (nth 5 fa2))))
(and
(equal (car file1) (car file2))
(not (eval predicate))))))
(setq list (cdr list)))
list)
(setq res (cons file1 res))))
(nreverse res))))
(defun dired-files-attributes (dir)
"Return a list of all file names and attributes from DIR.
List has a form of (file-name full-file-name (attribute-list))"
(mapcar
(lambda (file-name)
(let ((full-file-name (expand-file-name file-name dir)))
(list file-name
full-file-name
(file-attributes full-file-name))))
(directory-files dir)))
(defun dired-touch-initial (files)
"Create initial input value for `touch' command."
(let (initial)
(while files
(let ((current (nth 5 (file-attributes (car files)))))
(if (and initial (not (equal initial current)))
(setq initial (current-time) files nil)
(setq initial current))
(setq files (cdr files))))
(format-time-string "%Y%m%d%H%M.%S" initial)))
(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: ")
(if (eq op-symbol 'touch) (dired-touch-initial files))
op-symbol arg files))
(operation (concat program " " new-attribute))
failures)
(setq failures
(dired-bunch-files 10000
(function dired-check-process)
(append
(list operation program)
(if (eq op-symbol 'touch)
'("-t") nil)
(list 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-do-touch (&optional arg)
"Change the timestamp of the marked (or next ARG) files.
This calls touch."
(interactive "P")
(dired-do-chxxx "Timestamp" dired-touch-program 'touch arg))
(defun dired-bunch-files (max function args files)
(let (pending
past
(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 pending (nreverse pending)
failures (nconc (apply function (append args pending))
failures)
past (nconc past pending)
pending nil
pending-length 0))
(setcdr files pending)
(setq pending files)
(setq pending-length (+ thislength pending-length))
(setq files rest)))
(setq pending (nreverse pending))
(prog1
(nconc (apply function (append args pending))
failures)
(nconc past pending))))
(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-number (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 a `*' in COMMAND, surrounded by whitespace, this runs
COMMAND just once with the entire file list substituted there.
If there is no `*', but there is a `?' in COMMAND, surrounded by
whitespace, this runs COMMAND on each file individually with the
file name substituted for `?'.
Otherwise, this runs COMMAND on each file individually with the
file name added at the end of COMMAND (separated by a space).
`*' and `?' when not surrounded by whitespace have no special
significance for `dired-do-shell-command', and are passed through
normally to the shell, but you must confirm first. To pass `*' by
itself to the shell as a wildcard, type `*\"\"'.
If COMMAND produces output, it goes to a separate buffer.
This feature does not try to redisplay Dired buffers afterward, as
there's no telling what files COMMAND may have changed.
Type \\[dired-do-redisplay] to redisplay the marked files.
When COMMAND runs, its working directory is the top-level directory of
the Dired buffer, so output files usually are created there instead of
in a subdir.
In a noninteractive call (from Lisp code), you must specify
the list of file names explicitly with the FILE-LIST argument, which
can be produced by `dired-get-marked-files', for example."
(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 dired-star-subst-regexp command)))
(subst (not (string-match dired-quark-subst-regexp command)))
(star (not (string-match "\\*" command)))
(qmark (not (string-match "\\?" command))))
(if (cond ((not (or on-each subst))
(error "You can not combine `*' and `?' substitution marks"))
((and star (not on-each))
(y-or-n-p "Confirm--do you mean to use `*' as a wildcard? "))
((and qmark (not subst))
(y-or-n-p "Confirm--do you mean to use `?' as a wildcard? "))
(t))
(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 (or (string-match dired-star-subst-regexp command)
(string-match dired-quark-subst-regexp command))
(lambda (x)
(let ((retval command))
(while (string-match
"\\(^\\|[ \t]\\)\\([*?]\\)\\([ \t]\\|$\\)" retval)
(setq retval (replace-match x t t retval 2)))
retval))
(lambda (x) (concat command dired-mark-separator x)))))
(if on-each
(mapconcat stuff-it (mapcar 'shell-quote-argument file-list) ";")
(let ((files (mapconcat 'shell-quote-argument
file-list dired-mark-separator)))
(if (> (length file-list) 1)
(setq files (concat dired-mark-prefix files dired-mark-postfix)))
(funcall stuff-it files)))))
(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 (not (eq 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 backward.)
If you use this command with a prefix argument to kill the line
for a file that is a directory, which you have inserted in the
Dired buffer as a subdirectory, then it deletes that subdirectory
from the buffer as well.
To kill an entire subdirectory \(without killing its line in the
parent directory), 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)
(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))))
(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")
("\\.dz\\'" "" "dictunzip")
("\\.tbz\\'" ".tar" "bunzip2")
("\\.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
(let ((out-name (concat file ".gz")))
(and (or (not (file-exists-p out-name))
(y-or-n-p
(format "File %s already exists. Really compress? "
out-name)))
(not (dired-check-process (concat "Compressing " file)
"gzip" "-f" file))
(or (file-exists-p out-name)
(setq out-name (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 nil t))
(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))))
(message "%s" (concat (apply 'format qprompt qs-args)
(char-to-string 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.
Dired remembers switches specified with a prefix arg, so that reverting
the buffer will not reset them. However, using `dired-undo' to re-insert
or delete subdirectories can bypass this machinery. Hence, you sometimes
may have to reset some subdirectory switches after a `dired-undo'.
You can reset all subdirectory switches to the default using
\\<dired-mode-map>\\[dired-reset-subdir-switches].
See Info node `(emacs)Subdir switches' for more details."
(interactive "P\np")
(if (and test-for-subdir (dired-get-subdir))
(let* ((dir (dired-get-subdir))
(switches (cdr (assoc-string dir dired-switches-alist))))
(dired-insert-subdir
dir
(when arg
(read-string "Switches for listing: "
(or switches
dired-subdir-switches
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-reset-subdir-switches ()
"Set `dired-switches-alist' to nil and revert dired buffer."
(interactive)
(setq dired-switches-alist nil)
(revert-buffer))
(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-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))
(let ((default-directory directory))
(dired-insert-directory directory
(concat dired-actual-switches "d")
(list filename)))
(goto-char opoint)
(when marker-char
(let ((dired-marker-char
(if (integerp marker-char) marker-char dired-marker-char)))
(dired-mark nil)))
(goto-char opoint)
(let ((inserted-name (dired-get-filename 'verbatim)))
(if (file-name-directory inserted-name)
(let (props)
(end-of-line)
(forward-char (- (length inserted-name)))
(setq props (text-properties-at (point)))
(delete-char (length inserted-name))
(let ((pt (point)))
(insert filename)
(set-text-properties pt (point) props))
(forward-char 1))
(forward-line 1)))
(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-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)
"Create or update the line for FILE in all Dired buffers it would belong in."
(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
"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)
(dired-copy-file-recursive from to ok-flag dired-copy-preserve-time t
dired-recursive-copies))
(defun dired-copy-file-recursive (from to ok-flag &optional
preserve-time top recursive)
(let ((attrs (file-attributes from))
dirfailed)
(if (and recursive
(eq t (car attrs))
(or (eq recursive 'always)
(yes-or-no-p (format "Recursive copies of %s? " from))))
(let ((files
(condition-case err
(directory-files from nil dired-re-no-dot)
(file-error
(push (dired-make-relative from)
dired-create-files-failures)
(dired-log "Copying error for %s:\n%s\n" from err)
(setq dirfailed t)
nil))))
(if (eq recursive 'top) (setq recursive 'always)) (unless dirfailed
(if (file-exists-p to)
(or top (dired-handle-overwrite to))
(condition-case err
(make-directory to)
(file-error
(push (dired-make-relative from)
dired-create-files-failures)
(setq files nil)
(dired-log "Copying error for %s:\n%s\n" from err)))))
(dolist (file files)
(let ((thisfrom (expand-file-name file from))
(thisto (expand-file-name file to)))
(condition-case err
(dired-copy-file-recursive
thisfrom thisto
ok-flag preserve-time nil recursive)
(file-error
(push (dired-make-relative thisfrom)
dired-create-files-failures)
(dired-log "Copying error for %s:\n%s\n" thisfrom err))))))
(or top (dired-handle-overwrite to))
(condition-case err
(if (stringp (car attrs))
(make-symbolic-link (car attrs) to ok-flag)
(copy-file from to ok-flag dired-copy-preserve-time))
(file-date-error
(push (dired-make-relative from)
dired-create-files-failures)
(dired-log "Can't set date on %s:\n%s\n" from err))))))
(defun dired-rename-file (file newname ok-if-already-exists)
(dired-handle-overwrite newname)
(rename-file file newname ok-if-already-exists) (and (get-file-buffer file)
(with-current-buffer (get-file-buffer file)
(set-visited-file-name newname nil t)))
(dired-remove-file file)
(dired-rename-subdir file newname))
(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))))
(let ((cons (assoc-string (car elt) dired-switches-alist))
(cur-dir (dired-normalize-subdir
(dired-replace-in-string regexp newtext (car elt)))))
(setcar elt cur-dir)
(when cons (setcar cons cur-dir))))))
(defun dired-create-files (file-creator operation fn-list name-constructor
&optional marker-char)
(let (dired-create-files-failures 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
(push (dired-make-relative from)
failures)
(dired-log "%s `%s' to `%s' failed:\n%s\n"
operation from to err))))))))
fn-list))
(cond
(dired-create-files-failures
(setq failures (nconc failures dired-create-files-failures))
(dired-log-summary
(format "%s failed for %d file%s in %d requests"
operation (length failures)
(dired-plural-s (length failures))
total)
failures))
(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)
"Create a new file for each marked file.
Prompts user for target, which is a directory in which to create
the new files. Target may be a plain file if only one marked
file exists. The way the default for the target directory is
computed depends on the value of `dired-dwim-target-directory'.
OP-SYMBOL is the symbol for the operation. Function `dired-mark-pop-up'
will determine whether pop-ups are appropriate for this OP-SYMBOL.
FILE-CREATOR and OPERATION as in `dired-create-files'.
ARG as in `dired-get-marked-files'.
Optional arg MARKER-CHAR as in `dired-create-files'.
Optional arg OP1 is an alternate form for OPERATION if there is
only one file.
Optional arg HOW-TO is used to set the value of the into-dir variable
which determines how to treat target.
If into-dir is set to nil then target is not regarded as a directory,
there must be exactly one marked file, else error.
Else if into-dir is set to a list, then target is a generalized
directory (e.g. some sort of archive). The first element of into-dir
must be a function with at least four arguments:
operation as OPERATION above.
rfn-list a list of the relative names for the marked files.
fn-list a list of the absolute names for the marked files.
target.
The rest of into-dir are optional arguments.
Else into-dir is not a list. Target is a directory.
The marked file(s) are created inside the target directory.
If HOW-TO is not given (or nil), then into-dir is set to true if
target is a directory and otherwise to nil.
Else if HOW-TO is t, then into-dir is set to nil.
Else HOW-TO is assumed to be a function of one argument, target,
that looks at target and returns a value for the into-dir
variable. The function `dired-into-dir-with-symlinks' is provided
for the case (common when creating symlinks) that symbolic
links to directories are not to be considered as directories
(as `file-directory-p' would if HOW-TO had been nil)."
(or op1 (setq op1 operation))
(let* ((fn-list (dired-get-marked-files nil arg))
(rfn-list (mapcar (function dired-make-relative) fn-list))
(dired-one-file (and (consp fn-list) (null (cdr fn-list)) (car fn-list)))
(target-dir (dired-dwim-target-directory))
(default (and dired-one-file
(expand-file-name (file-name-nondirectory (car fn-list))
target-dir)))
(target (expand-file-name (dired-mark-read-file-name
(concat (if dired-one-file op1 operation) " %s to: ")
target-dir op-symbol arg rfn-list default)))
(into-dir (cond ((null how-to)
(if (and (memq system-type '(ms-dos windows-nt cygwin))
(eq op-symbol 'move)
dired-one-file
(string= (downcase
(expand-file-name (car fn-list)))
(downcase
(expand-file-name target)))
(not (string=
(file-name-nondirectory (car fn-list))
(file-name-nondirectory target))))
nil
(file-directory-p target)))
((eq how-to t) nil)
(t (funcall how-to target)))))
(if (and (consp into-dir) (functionp (car into-dir)))
(apply (car into-dir) operation rfn-list fn-list target (cdr into-dir))
(if (not (or dired-one-file 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
&optional default)
(dired-mark-pop-up
nil op-symbol files
(function read-file-name)
(format prompt (dired-mark-prompt arg files)) dir default))
(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))))
(defvar dired-copy-how-to-fn nil
"nil or a function used by `dired-do-copy' to determine target.
See HOW-TO argument for `dired-do-create-files'.")
(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. The default
suggested for the target directory depends on the value of
`dired-dwim-target', which see.
This command copies symbolic links by creating new ones,
like `cp -d'."
(interactive "P")
(let ((dired-recursive-copies dired-recursive-copies))
(dired-do-create-files 'copy (function dired-copy-file)
"Copy"
arg dired-keep-marker-copy
nil dired-copy-how-to-fn)))
(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. The default
suggested for the target directory depends on the value of
`dired-dwim-target', which see.
For relative symlinks, use \\[dired-do-relsymlink]."
(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. The default
suggested for the target directory depends on the value of
`dired-dwim-target', which see."
(interactive "P")
(dired-do-create-files 'hardlink (function dired-hardlink)
"Hardlink" arg dired-keep-marker-hardlink))
(defun dired-hardlink (file newname &optional ok-if-already-exists)
(dired-handle-overwrite newname)
(add-name-to-file file newname ok-if-already-exists)
(dired-relist-file file))
(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.
This command also renames any buffers that are visiting the files.
The default suggested for the target directory depends on the value
of `dired-dwim-target', which see."
(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-name 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-name (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-name
(equal 0 (prefix-numeric-value current-prefix-arg)))
(arg
(if whole-name nil current-prefix-arg))
(regexp
(dired-read-regexp
(concat (if whole-name "Abs. " "") operation " from (regexp): ")))
(newname
(read-string
(concat (if whole-name "Abs. " "") operation " " regexp " to: "))))
(list regexp newname arg whole-name)))
(defun dired-do-rename-regexp (regexp newname &optional arg whole-name)
"Rename selected files whose names match REGEXP to NEWNAME.
With non-zero prefix argument ARG, the command operates on the next ARG
files. Otherwise, it operates on all the marked files, or the current
file if none are marked.
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-name dired-keep-marker-rename))
(defun dired-do-copy-regexp (regexp newname &optional arg whole-name)
"Copy selected files whose names match REGEXP to NEWNAME.
See function `dired-do-rename-regexp' for more info."
(interactive (dired-mark-read-regexp "Copy"))
(let ((dired-recursive-copies nil)) (dired-do-create-files-regexp
(function dired-copy-file)
(if dired-copy-preserve-time "Copy [-p]" "Copy")
arg regexp newname whole-name dired-keep-marker-copy)))
(defun dired-do-hardlink-regexp (regexp newname &optional arg whole-name)
"Hardlink selected files whose names match 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-name dired-keep-marker-hardlink))
(defun dired-do-symlink-regexp (regexp newname &optional arg whole-name)
"Symlink selected files whose names match 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-name 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.
Dired remembers switches specified with a prefix arg, so that reverting
the buffer will not reset them. However, using `dired-undo' to re-insert
or delete subdirectories can bypass this machinery. Hence, you sometimes
may have to reset some subdirectory switches after a `dired-undo'.
You can reset all subdirectory switches to the default using
\\<dired-mode-map>\\[dired-reset-subdir-switches].
See Info node `(emacs)Subdir switches' for more details."
(interactive
(list (dired-get-filename)
(if current-prefix-arg
(read-string "Switches for listing: "
(or dired-subdir-switches 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: "
(or dired-subdir-switches dired-actual-switches)))))
(setq dirname (file-name-as-directory (expand-file-name dirname)))
(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))
(cons (assoc-string dirname dired-switches-alist))
(modflag (buffer-modified-p))
(old-switches switches)
switches-have-R mark-alist case-fold-search buffer-read-only)
(and (not switches) cons (setq switches (cdr cons)))
(dired-insert-subdir-validate dirname switches)
(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))
(when old-switches
(if cons
(setcdr cons switches)
(push (cons dirname switches) dired-switches-alist)))
(when switches-have-R
(dired-build-subdir-alist switches)
(setq switches (dired-replace-in-string "R" "" switches))
(dolist (cur-ass dired-subdir-alist)
(let ((cur-dir (car cur-ass)))
(and (dired-in-this-tree cur-dir dirname)
(let ((cur-cons (assoc-string cur-dir dired-switches-alist)))
(if cur-cons
(setcdr cur-cons switches)
(push (cons cur-dir switches) dired-switches-alist)))))))
(dired-initial-position dirname)
(save-excursion (dired-mark-remembered mark-alist))
(restore-buffer-modified-p modflag)))
(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))
(let ((real-switches (or switches dired-subdir-switches)))
(when real-switches
(let (case-fold-search)
(mapcar
(function
(lambda (x)
(or (eq (null (string-match x real-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 kill-root)
"Kill all proper subdirs of DIRNAME, excluding DIRNAME itself.
Interactively, you can kill DIRNAME as well by using a prefix argument.
In interactive use, the command prompts for DIRNAME.
When called from Lisp, if REMEMBER-MARKS is non-nil, return an alist
of marked files. If KILL-ROOT is non-nil, kill DIRNAME as well."
(interactive "DKill tree below directory: \ni\nP")
(setq dirname (file-name-as-directory (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))
(and (or kill-root (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)
(save-excursion
(let ((begin (point)))
(let ((dired-actual-switches
(or switches
dired-subdir-switches
(dired-replace-in-string "R" "" dired-actual-switches))))
(if (equal dirname (car (car (last dired-subdir-alist))))
(dired-readin-insert)
(dired-insert-directory dirname dired-actual-switches nil nil t)))
(list begin (point)))))
(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))
(modflag (buffer-modified-p))
(cur-dir (dired-current-directory))
(cons (assoc-string cur-dir dired-switches-alist))
buffer-read-only)
(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)
(when cons
(setq dired-switches-alist (delete cons dired-switches-alist)))
(restore-buffer-modified-p modflag))))
(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)
(let ((modflag (buffer-modified-p)))
(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))
(restore-buffer-modified-p modflag)))
(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 ((modflag (buffer-modified-p))
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)))))
(restore-buffer-modified-p modflag)))
(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 nil nil 'dired-nondirectory-p)))
(defun dired-do-query-replace-regexp (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], RET or q), you can resume the query replace
with the command \\[tags-loop-continue]."
(interactive
(let ((common
(query-replace-read-args
"Query replace regexp in marked files" t t)))
(list (nth 0 common) (nth 1 common) (nth 2 common))))
(dolist (file (dired-get-marked-files nil nil 'dired-nondirectory-p))
(let ((buffer (get-file-buffer file)))
(if (and buffer (with-current-buffer buffer
buffer-read-only))
(error "File `%s' is visited read-only" file))))
(tags-query-replace from to delimited
'(dired-get-marked-files nil nil 'dired-nondirectory-p)))
(defun dired-nondirectory-p (file)
(not (file-directory-p file)))
(defun dired-show-file-type (file &optional deref-symlinks)
"Print the type of FILE, according to the `file' command.
If FILE is a symbolic link and the optional argument DEREF-SYMLINKS is
true then the type of the file linked to by FILE is printed instead."
(interactive (list (dired-get-filename t) current-prefix-arg))
(with-temp-buffer
(if deref-symlinks
(call-process "file" nil t t "-L" "--" file)
(call-process "file" nil t t "--" file))
(when (bolp)
(backward-delete-char 1))
(message "%s" (buffer-string))))
(provide 'dired-aux)