Merge from emacs-24; up to 2012-04-22T13:58:00Z!cyd@gnu.org
[bpt/emacs.git] / lisp / dired-aux.el
CommitLineData
276f1d00 1;;; dired-aux.el --- less commonly used parts of dired
dd87891b 2
acaf905b 3;; Copyright (C) 1985-1986, 1992, 1994, 1998, 2000-2012
e9bffc61 4;; Free Software Foundation, Inc.
3a801d0c 5
2f14b48d 6;; Author: Sebastian Kremer <sk@thp.uni-koeln.de>.
0acdb863 7;; Maintainer: FSF
565132a3 8;; Keywords: files
bd78fa1d 9;; Package: emacs
e5167999 10
dd87891b
RS
11;; This file is part of GNU Emacs.
12
eb3fa2cf 13;; GNU Emacs is free software: you can redistribute it and/or modify
dd87891b 14;; it under the terms of the GNU General Public License as published by
eb3fa2cf
GM
15;; the Free Software Foundation, either version 3 of the License, or
16;; (at your option) any later version.
dd87891b
RS
17
18;; GNU Emacs is distributed in the hope that it will be useful,
19;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21;; GNU General Public License for more details.
22
23;; You should have received a copy of the GNU General Public License
eb3fa2cf 24;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
dd87891b 25
2f14b48d
ER
26;;; Commentary:
27
e41b2db1
ER
28;; The parts of dired mode not normally used. This is a space-saving hack
29;; to avoid having to load a large mode when all that's wanted are a few
30;; functions.
31
dd87891b
RS
32;; Rewritten in 1990/1991 to add tree features, file marking and
33;; sorting by Sebastian Kremer <sk@thp.uni-koeln.de>.
34;; Finished up by rms in 1992.
35
2f14b48d
ER
36;;; Code:
37
55d77548
RS
38;; We need macros in dired.el to compile properly,
39;; and we call subroutines in it too.
40(require 'dired)
6482fcac 41
c62a8073
RS
42(defvar dired-create-files-failures nil
43 "Variable where `dired-create-files' records failing file names.
44Functions that operate recursively can store additional names
45into this list; they also should call `dired-log' to log the errors.")
46
dd87891b
RS
47;;; 15K
48;;;###begin dired-cmd.el
49;; Diffing and compressing
50
edb8d73e
FP
51(defconst dired-star-subst-regexp "\\(^\\|[ \t]\\)\\*\\([ \t]\\|$\\)")
52(defconst dired-quark-subst-regexp "\\(^\\|[ \t]\\)\\?\\([ \t]\\|$\\)")
53
dd87891b
RS
54;;;###autoload
55(defun dired-diff (file &optional switches)
56 "Compare file at point with file FILE using `diff'.
a1af8dcf
EZ
57FILE defaults to the file at the mark. (That's the mark set by
58\\[set-mark-command], not by Dired's \\[dired-mark] command.)
ace6c69c 59The prompted-for FILE is the first file given to `diff'.
fe5e3a2a 60With prefix arg, prompt for second argument SWITCHES,
ace6c69c 61which is the string of command switches for `diff'."
dd87891b 62 (interactive
e237085f 63 (let* ((current (dired-get-filename t))
72b57560
JL
64 ;; Get the file at the mark.
65 (file-at-mark (if (mark t)
66 (save-excursion (goto-char (mark t))
67 (dired-get-filename t t))))
68 ;; Use it as default if it's not the same as the current file,
69 ;; and the target dir is the current dir or the mark is active.
70 (default (if (and (not (equal file-at-mark current))
71 (or (equal (dired-dwim-target-directory)
72 (dired-current-directory))
73 mark-active))
74 file-at-mark))
75 (target-dir (if default
76 (dired-current-directory)
77 (dired-dwim-target-directory)))
78 (defaults (dired-dwim-target-defaults (list current) target-dir)))
231596b2 79 (require 'diff)
e237085f
JL
80 (list
81 (minibuffer-with-setup-hook
82 (lambda ()
83 (set (make-local-variable 'minibuffer-default-add-function) nil)
84 (setq minibuffer-default defaults))
72b57560
JL
85 (read-file-name
86 (format "Diff %s with%s: " current
87 (if default (format " (default %s)" default) ""))
88 target-dir default t))
e237085f
JL
89 (if current-prefix-arg
90 (read-string "Options for diff: "
91 (if (stringp diff-switches)
92 diff-switches
93 (mapconcat 'identity diff-switches " ")))))))
ad974e9e
JL
94 (let ((current (dired-get-filename t)))
95 (when (or (equal (expand-file-name file)
96 (expand-file-name current))
97 (and (file-directory-p file)
98 (equal (expand-file-name current file)
99 (expand-file-name current))))
100 (error "Attempt to compare the file to itself"))
101 (diff file current switches)))
dd87891b
RS
102
103;;;###autoload
104(defun dired-backup-diff (&optional switches)
105 "Diff this file with its backup file or vice versa.
106Uses the latest backup, if there are several numerical backups.
107If this file is a backup, diff it with its original.
fe5e3a2a
RS
108The backup file is the first file given to `diff'.
109With prefix arg, prompt for argument SWITCHES which is options for `diff'."
110 (interactive
111 (if current-prefix-arg
112 (list (read-string "Options for diff: "
113 (if (stringp diff-switches)
114 diff-switches
115 (mapconcat 'identity diff-switches " "))))
116 nil))
117 (diff-backup (dired-get-filename) switches))
dd87891b 118
3659a2b8 119;;;###autoload
d1c553c8
RS
120(defun dired-compare-directories (dir2 predicate)
121 "Mark files with different file attributes in two dired buffers.
122Compare file attributes of files in the current directory
123with file attributes in directory DIR2 using PREDICATE on pairs of files
124with the same name. Mark files for which PREDICATE returns non-nil.
999bd52a 125Mark files with different names if PREDICATE is nil (or interactively
3659a2b8 126with empty input at the predicate prompt).
d1c553c8
RS
127
128PREDICATE is a Lisp expression that can refer to the following variables:
129
130 size1, size2 - file size in bytes
131 mtime1, mtime2 - last modification time in seconds, as a float
132 fa1, fa2 - list of file attributes
133 returned by function `file-attributes'
134
135 where 1 refers to attribute of file in the current dired buffer
136 and 2 to attribute of file in second dired buffer.
137
138Examples of PREDICATE:
139
140 (> mtime1 mtime2) - mark newer files
141 (not (= size1 size2)) - mark files with different sizes
142 (not (string= (nth 8 fa1) (nth 8 fa2))) - mark files with different modes
143 (not (and (= (nth 2 fa1) (nth 2 fa2)) - mark files with different UID
144 (= (nth 3 fa1) (nth 3 fa2)))) and GID."
145 (interactive
e237085f
JL
146 (list
147 (let* ((target-dir (dired-dwim-target-directory))
148 (defaults (dired-dwim-target-defaults nil target-dir)))
149 (minibuffer-with-setup-hook
150 (lambda ()
151 (set (make-local-variable 'minibuffer-default-add-function) nil)
152 (setq minibuffer-default defaults))
153 (read-directory-name (format "Compare %s with: "
154 (dired-current-directory))
155 target-dir target-dir t)))
156 (read-from-minibuffer "Mark if (lisp expr or RET): " nil nil t nil "nil")))
d1c553c8
RS
157 (let* ((dir1 (dired-current-directory))
158 (file-alist1 (dired-files-attributes dir1))
159 (file-alist2 (dired-files-attributes dir2))
5176af43
RS
160 file-list1 file-list2)
161 (setq file-alist1 (delq (assoc "." file-alist1) file-alist1))
162 (setq file-alist1 (delq (assoc ".." file-alist1) file-alist1))
163 (setq file-alist2 (delq (assoc "." file-alist2) file-alist2))
164 (setq file-alist2 (delq (assoc ".." file-alist2) file-alist2))
165 (setq file-list1 (mapcar
d1c553c8
RS
166 'cadr
167 (dired-file-set-difference
168 file-alist1 file-alist2
5176af43
RS
169 predicate))
170 file-list2 (mapcar
d1c553c8
RS
171 'cadr
172 (dired-file-set-difference
173 file-alist2 file-alist1
5176af43 174 predicate)))
d1c553c8
RS
175 (dired-fun-in-all-buffers
176 dir1 nil
177 (lambda ()
178 (dired-mark-if
179 (member (dired-get-filename nil t) file-list1) nil)))
180 (dired-fun-in-all-buffers
181 dir2 nil
182 (lambda ()
183 (dired-mark-if
184 (member (dired-get-filename nil t) file-list2) nil)))
185 (message "Marked in dir1: %s files, in dir2: %s files"
186 (length file-list1)
187 (length file-list2))))
188
189(defun dired-file-set-difference (list1 list2 predicate)
190 "Combine LIST1 and LIST2 using a set-difference operation.
191The result list contains all file items that appear in LIST1 but not LIST2.
192This is a non-destructive function; it makes a copy of the data if necessary
193to avoid corrupting the original LIST1 and LIST2.
194PREDICATE (see `dired-compare-directories') is an additional match
195condition. Two file items are considered to match if they are equal
196*and* PREDICATE evaluates to t."
197 (if (or (null list1) (null list2))
198 list1
199 (let (res)
200 (dolist (file1 list1)
201 (unless (let ((list list2))
202 (while (and list
203 (not (let* ((file2 (car list))
9375be01
JPW
204 (fa1 (car (cddr file1)))
205 (fa2 (car (cddr file2)))
d1c553c8
RS
206 (size1 (nth 7 fa1))
207 (size2 (nth 7 fa2))
208 (mtime1 (float-time (nth 5 fa1)))
209 (mtime2 (float-time (nth 5 fa2))))
210 (and
211 (equal (car file1) (car file2))
212 (not (eval predicate))))))
213 (setq list (cdr list)))
214 list)
215 (setq res (cons file1 res))))
216 (nreverse res))))
217
218(defun dired-files-attributes (dir)
219 "Return a list of all file names and attributes from DIR.
5a0c3f56 220List has a form of (file-name full-file-name (attribute-list))."
d1c553c8
RS
221 (mapcar
222 (lambda (file-name)
223 (let ((full-file-name (expand-file-name file-name dir)))
224 (list file-name
225 full-file-name
226 (file-attributes full-file-name))))
227 (directory-files dir)))
228\f
2cc8e51a 229;;; Change file attributes
52f134ee 230
dd87891b 231(defun dired-do-chxxx (attribute-name program op-symbol arg)
2cc8e51a 232 ;; Change file attributes (group, owner, timestamp) of marked files and
dd87891b
RS
233 ;; refresh their file lines.
234 ;; ATTRIBUTE-NAME is a string describing the attribute to the user.
235 ;; PROGRAM is the program used to change the attribute.
2cc8e51a
JL
236 ;; OP-SYMBOL is the type of operation (for use in `dired-mark-pop-up').
237 ;; ARG describes which files to use, as in `dired-get-marked-files'.
dd87891b 238 (let* ((files (dired-get-marked-files t arg))
64b51947
CY
239 (default (and (eq op-symbol 'touch)
240 (stringp (car files))
241 (format-time-string "%Y%m%d%H%M.%S"
242 (nth 5 (file-attributes (car files))))))
243 (prompt (concat "Change " attribute-name " of %s to"
244 (if (eq op-symbol 'touch)
245 " (default now): "
246 ": ")))
247 (new-attribute (dired-mark-read-string prompt nil op-symbol
30009afd
DA
248 arg files default
249 (cond ((eq op-symbol 'chown)
250 (system-users))
251 ((eq op-symbol 'chgrp)
252 (system-groups)))))
dd87891b
RS
253 (operation (concat program " " new-attribute))
254 failures)
255 (setq failures
256 (dired-bunch-files 10000
257 (function dired-check-process)
edb8d73e 258 (append
3ccd3160 259 (list operation program)
64b51947
CY
260 (unless (string-equal new-attribute "")
261 (if (eq op-symbol 'touch)
262 (list "-t" new-attribute)
263 (list new-attribute)))
05a455e2
RS
264 (if (string-match "gnu" system-configuration)
265 '("--") nil))
dd87891b
RS
266 files))
267 (dired-do-redisplay arg);; moves point if ARG is an integer
268 (if failures
269 (dired-log-summary
270 (format "%s: error" operation)
271 nil))))
272
273;;;###autoload
274(defun dired-do-chmod (&optional arg)
275 "Change the mode of the marked (or next ARG) files.
822b17d3 276Symbolic modes like `g+w' are allowed."
dd87891b 277 (interactive "P")
822b17d3 278 (let* ((files (dired-get-marked-files t arg))
78be566d
JL
279 (modestr (and (stringp (car files))
280 (nth 8 (file-attributes (car files)))))
281 (default
282 (and (stringp modestr)
283 (string-match "^.\\(...\\)\\(...\\)\\(...\\)$" modestr)
284 (replace-regexp-in-string
285 "-" ""
286 (format "u=%s,g=%s,o=%s"
287 (match-string 1 modestr)
288 (match-string 2 modestr)
289 (match-string 3 modestr)))))
822b17d3 290 (modes (dired-mark-read-string
64b51947 291 "Change mode of %s to: "
a0bf2bcd 292 nil 'chmod arg files default))
64b51947 293 num-modes)
64b51947
CY
294 (cond ((equal modes "")
295 ;; We used to treat empty input as DEFAULT, but that is not
296 ;; such a good idea (Bug#9361).
297 (error "No file mode specified"))
298 ((string-match "^[0-7]+" modes)
299 (setq num-modes (string-to-number modes 8))))
300
822b17d3
MC
301 (dolist (file files)
302 (set-file-modes
303 file
304 (if num-modes num-modes
305 (file-modes-symbolic-to-number modes (file-modes file)))))
306 (dired-do-redisplay arg)))
dd87891b
RS
307
308;;;###autoload
309(defun dired-do-chgrp (&optional arg)
310 "Change the group of the marked (or next ARG) files."
311 (interactive "P")
a40dbafc 312 (if (memq system-type '(ms-dos windows-nt))
55535639 313 (error "chgrp not supported on this system"))
dd87891b
RS
314 (dired-do-chxxx "Group" "chgrp" 'chgrp arg))
315
316;;;###autoload
317(defun dired-do-chown (&optional arg)
318 "Change the owner of the marked (or next ARG) files."
319 (interactive "P")
a40dbafc 320 (if (memq system-type '(ms-dos windows-nt))
55535639 321 (error "chown not supported on this system"))
dd87891b
RS
322 (dired-do-chxxx "Owner" dired-chown-program 'chown arg))
323
05dcf18a 324;;;###autoload
3ccd3160
JL
325(defun dired-do-touch (&optional arg)
326 "Change the timestamp of the marked (or next ARG) files.
327This calls touch."
328 (interactive "P")
329 (dired-do-chxxx "Timestamp" dired-touch-program 'touch arg))
330
dd87891b
RS
331;; Process all the files in FILES in batches of a convenient size,
332;; by means of (FUNCALL FUNCTION ARGS... SOME-FILES...).
333;; Batches are chosen to need less than MAX chars for the file names,
334;; allowing 3 extra characters of separator per file name.
335(defun dired-bunch-files (max function args files)
336 (let (pending
e5369aad 337 past
dd87891b
RS
338 (pending-length 0)
339 failures)
340 ;; Accumulate files as long as they fit in MAX chars,
341 ;; then process the ones accumulated so far.
342 (while files
343 (let* ((thisfile (car files))
344 (thislength (+ (length thisfile) 3))
345 (rest (cdr files)))
346 ;; If we have at least 1 pending file
347 ;; and this file won't fit in the length limit, process now.
348 (if (and pending (> (+ thislength pending-length) max))
e5369aad
RS
349 (setq pending (nreverse pending)
350 ;; The elements of PENDING are now in forward order.
351 ;; Do the operation and record failures.
352 failures (nconc (apply function (append args pending))
353 failures)
4c36be58 354 ;; Transfer the elements of PENDING onto PAST
e5369aad
RS
355 ;; and clear it out. Now PAST contains the first N files
356 ;; specified (for some N), and FILES contains the rest.
357 past (nconc past pending)
dd87891b
RS
358 pending nil
359 pending-length 0))
360 ;; Do (setq pending (cons thisfile pending))
361 ;; but reuse the cons that was in `files'.
362 (setcdr files pending)
363 (setq pending files)
364 (setq pending-length (+ thislength pending-length))
365 (setq files rest)))
e5369aad
RS
366 (setq pending (nreverse pending))
367 (prog1
368 (nconc (apply function (append args pending))
369 failures)
370 ;; Now the original list FILES has been put back as it was.
371 (nconc past pending))))
dd87891b
RS
372
373;;;###autoload
374(defun dired-do-print (&optional arg)
375 "Print the marked (or next ARG) files.
376Uses the shell command coming from variables `lpr-command' and
377`lpr-switches' as default."
378 (interactive "P")
379 (let* ((file-list (dired-get-marked-files t arg))
380 (command (dired-mark-read-string
381 "Print %s with: "
c572e732
RS
382 (mapconcat 'identity
383 (cons lpr-command
384 (if (stringp lpr-switches)
385 (list lpr-switches)
386 lpr-switches))
387 " ")
dd87891b
RS
388 'print arg file-list)))
389 (dired-run-shell-command (dired-shell-stuff-it command file-list nil))))
390
64b51947 391(defun dired-mark-read-string (prompt initial op-symbol arg files
30009afd 392 &optional default-value collection)
64b51947
CY
393 "Read args for a Dired marked-files command, prompting with PROMPT.
394Return the user input (a string).
395
396INITIAL, if non-nil, is the initial minibuffer input.
397OP-SYMBOL is an operation symbol (see `dired-no-confirm').
398ARG is normally the prefix argument for the calling command.
399FILES should be a list of file names.
400
a0bf2bcd
CY
401DEFAULT-VALUE, if non-nil, should be a \"standard\" value or list
402of such values, available via history commands. Note that if the
403user enters empty input, this function returns the empty string,
12e10e61
GM
404not DEFAULT-VALUE.
405
406Optional argument COLLECTION is a collection of possible completions,
407suitable for use by `completing-read'."
64b51947 408 (dired-mark-pop-up nil op-symbol files
30009afd 409 'completing-read
64b51947 410 (format prompt (dired-mark-prompt arg files))
30009afd 411 collection nil nil initial nil default-value nil))
83fadedf 412\f
2d051399
RS
413;;; Cleaning a directory: flagging some backups for deletion.
414
6482fcac
RS
415(defvar dired-file-version-alist)
416
05dcf18a 417;;;###autoload
2d051399
RS
418(defun dired-clean-directory (keep)
419 "Flag numerical backups for deletion.
420Spares `dired-kept-versions' latest versions, and `kept-old-versions' oldest.
421Positive prefix arg KEEP overrides `dired-kept-versions';
422Negative prefix arg KEEP overrides `kept-old-versions' with KEEP made positive.
423
424To clear the flags on these files, you can use \\[dired-flag-backup-files]
425with a prefix argument."
426 (interactive "P")
427 (setq keep (if keep (prefix-numeric-value keep) dired-kept-versions))
428 (let ((early-retention (if (< keep 0) (- keep) kept-old-versions))
429 (late-retention (if (<= keep 0) dired-kept-versions keep))
430 (dired-file-version-alist ()))
431 (message "Cleaning numerical backups (keeping %d late, %d old)..."
432 late-retention early-retention)
433 ;; Look at each file.
434 ;; If the file has numeric backup versions,
435 ;; put on dired-file-version-alist an element of the form
436 ;; (FILENAME . VERSION-NUMBER-LIST)
437 (dired-map-dired-file-lines (function dired-collect-file-versions))
438 ;; Sort each VERSION-NUMBER-LIST,
439 ;; and remove the versions not to be deleted.
440 (let ((fval dired-file-version-alist))
441 (while fval
442 (let* ((sorted-v-list (cons 'q (sort (cdr (car fval)) '<)))
443 (v-count (length sorted-v-list)))
444 (if (> v-count (+ early-retention late-retention))
445 (rplacd (nthcdr early-retention sorted-v-list)
446 (nthcdr (- v-count late-retention)
447 sorted-v-list)))
448 (rplacd (car fval)
449 (cdr sorted-v-list)))
450 (setq fval (cdr fval))))
451 ;; Look at each file. If it is a numeric backup file,
452 ;; find it in a VERSION-NUMBER-LIST and maybe flag it for deletion.
453 (dired-map-dired-file-lines (function dired-trample-file-versions))
454 (message "Cleaning numerical backups...done")))
455
456;;; Subroutines of dired-clean-directory.
457
458(defun dired-map-dired-file-lines (fun)
459 ;; Perform FUN with point at the end of each non-directory line.
57dabf6b 460 ;; FUN takes one argument, the absolute filename.
2d051399
RS
461 (save-excursion
462 (let (file buffer-read-only)
463 (goto-char (point-min))
464 (while (not (eobp))
465 (save-excursion
466 (and (not (looking-at dired-re-dir))
467 (not (eolp))
468 (setq file (dired-get-filename nil t)) ; nil on non-file
469 (progn (end-of-line)
470 (funcall fun file))))
471 (forward-line 1)))))
472
06b60517
JB
473(defvar backup-extract-version-start) ; used in backup-extract-version
474
2d051399 475(defun dired-collect-file-versions (fn)
61c6f873
RS
476 (let ((fn (file-name-sans-versions fn)))
477 ;; Only do work if this file is not already in the alist.
478 (if (assoc fn dired-file-version-alist)
479 nil
480 ;; If it looks like file FN has versions, return a list of the versions.
481 ;;That is a list of strings which are file names.
f9acc7fb 482 ;;The caller may want to flag some of these files for deletion.
61c6f873
RS
483 (let* ((base-versions
484 (concat (file-name-nondirectory fn) ".~"))
afbd0a53 485 (backup-extract-version-start (length base-versions))
61c6f873
RS
486 (possibilities (file-name-all-completions
487 base-versions
488 (file-name-directory fn)))
489 (versions (mapcar 'backup-extract-version possibilities)))
490 (if versions
491 (setq dired-file-version-alist
492 (cons (cons fn versions)
493 dired-file-version-alist)))))))
2d051399
RS
494
495(defun dired-trample-file-versions (fn)
496 (let* ((start-vn (string-match "\\.~[0-9]+~$" fn))
497 base-version-list)
498 (and start-vn
499 (setq base-version-list ; there was a base version to which
500 (assoc (substring fn 0 start-vn) ; this looks like a
501 dired-file-version-alist)) ; subversion
027a4b6b 502 (not (memq (string-to-number (substring fn (+ 2 start-vn)))
2d051399
RS
503 base-version-list)) ; this one doesn't make the cut
504 (progn (beginning-of-line)
505 (delete-char 1)
506 (insert dired-del-marker)))))
83fadedf 507\f
dd87891b 508;;; Shell commands
dd87891b 509
905eb9ff
JL
510(declare-function mailcap-file-default-commands "mailcap" (files))
511
512(defun minibuffer-default-add-dired-shell-commands ()
b8f908b3
JL
513 "Return a list of all commands associated with current dired files.
514This function is used to add all related commands retrieved by `mailcap'
905eb9ff
JL
515to the end of the list of defaults just after the default value."
516 (interactive)
517 (let ((commands (and (boundp 'files) (require 'mailcap nil t)
518 (mailcap-file-default-commands files))))
519 (if (listp minibuffer-default)
520 (append minibuffer-default commands)
521 (cons minibuffer-default commands))))
2f8a5963 522
1906dec4 523;; This is an extra function so that you can redefine it, e.g., to use gmhist.
dd87891b 524(defun dired-read-shell-command (prompt arg files)
f69fd0d2
CY
525 "Read a dired shell command.
526PROMPT should be a format string with one \"%s\" format sequence,
527which is replaced by the value returned by `dired-mark-prompt',
528with ARG and FILES as its arguments. FILES should be a list of
529file names. The result is used as the prompt.
530
531This normally reads using `read-shell-command', but if the
532`dired-x' package is loaded, use `dired-guess-shell-command' to
533offer a smarter default choice of shell command."
905eb9ff
JL
534 (minibuffer-with-setup-hook
535 (lambda ()
536 (set (make-local-variable 'minibuffer-default-add-function)
537 'minibuffer-default-add-dired-shell-commands))
d6e96966 538 (setq prompt (format prompt (dired-mark-prompt arg files)))
f69fd0d2 539 (if (functionp 'dired-guess-shell-command)
d6e96966 540 (dired-mark-pop-up nil 'shell files
f69fd0d2 541 'dired-guess-shell-command prompt files)
d6e96966 542 (dired-mark-pop-up nil 'shell files
f69fd0d2 543 'read-shell-command prompt nil nil))))
dd87891b 544
5ec0c892
JL
545;;;###autoload
546(defun dired-do-async-shell-command (command &optional arg file-list)
547 "Run a shell command COMMAND on the marked files asynchronously.
548
549Like `dired-do-shell-command' but if COMMAND doesn't end in ampersand,
550adds `* &' surrounded by whitespace and executes the command asynchronously.
551The output appears in the buffer `*Async Shell Command*'."
552 (interactive
553 (let ((files (dired-get-marked-files t current-prefix-arg)))
554 (list
555 ;; Want to give feedback whether this file or marked files are used:
556 (dired-read-shell-command "& on %s: " current-prefix-arg files)
557 current-prefix-arg
558 files)))
559 (unless (string-match "[*?][ \t]*\\'" command)
560 (setq command (concat command " *")))
561 (unless (string-match "&[ \t]*\\'" command)
562 (setq command (concat command " &")))
563 (dired-do-shell-command command arg file-list))
564
dd87891b
RS
565;; The in-background argument is only needed in Emacs 18 where
566;; shell-command doesn't understand an appended ampersand `&'.
567;;;###autoload
01db6210 568(defun dired-do-shell-command (command &optional arg file-list)
6482fcac
RS
569 "Run a shell command COMMAND on the marked files.
570If no files are marked or a specific numeric prefix arg is given,
571the next ARG files are used. Just \\[universal-argument] means the current file.
572The prompt mentions the file(s) or the marker, as appropriate.
573
eab9ed67
RS
574If there is a `*' in COMMAND, surrounded by whitespace, this runs
575COMMAND just once with the entire file list substituted there.
6482fcac 576
eab9ed67
RS
577If there is no `*', but there is a `?' in COMMAND, surrounded by
578whitespace, this runs COMMAND on each file individually with the
579file name substituted for `?'.
dd87891b 580
eab9ed67
RS
581Otherwise, this runs COMMAND on each file individually with the
582file name added at the end of COMMAND (separated by a space).
d984dbc1 583
eab9ed67
RS
584`*' and `?' when not surrounded by whitespace have no special
585significance for `dired-do-shell-command', and are passed through
09044622
GM
586normally to the shell, but you must confirm first.
587
588If you want to use `*' as a shell wildcard with whitespace around
589it, write `*\"\"' in place of just `*'. This is equivalent to just
590`*' in the shell, but avoids Dired's special handling.
dd87891b 591
eab9ed67
RS
592If COMMAND produces output, it goes to a separate buffer.
593
594This feature does not try to redisplay Dired buffers afterward, as
595there's no telling what files COMMAND may have changed.
596Type \\[dired-do-redisplay] to redisplay the marked files.
597
5a0c3f56
JB
598When COMMAND runs, its working directory is the top-level directory
599of the Dired buffer, so output files usually are created there
600instead of in a subdir.
9e545350
KH
601
602In a noninteractive call (from Lisp code), you must specify
40c50be3
EZ
603the list of file names explicitly with the FILE-LIST argument, which
604can be produced by `dired-get-marked-files', for example."
dd87891b
RS
605;;Functions dired-run-shell-command and dired-shell-stuff-it do the
606;;actual work and can be redefined for customization.
01db6210
RS
607 (interactive
608 (let ((files (dired-get-marked-files t current-prefix-arg)))
609 (list
610 ;; Want to give feedback whether this file or marked files are used:
611 (dired-read-shell-command (concat "! on "
612 "%s: ")
613 current-prefix-arg
614 files)
615 current-prefix-arg
616 files)))
edb8d73e 617 (let* ((on-each (not (string-match dired-star-subst-regexp command)))
e52c37fa
GM
618 (no-subst (not (string-match dired-quark-subst-regexp command)))
619 (star (string-match "\\*" command))
620 (qmark (string-match "\\?" command)))
eab9ed67
RS
621 ;; Get confirmation for wildcards that may have been meant
622 ;; to control substitution of a file name or the file name list.
e52c37fa 623 (if (cond ((not (or on-each no-subst))
edb8d73e 624 (error "You can not combine `*' and `?' substitution marks"))
e52c37fa 625 ((and star on-each)
eab9ed67 626 (y-or-n-p "Confirm--do you mean to use `*' as a wildcard? "))
e52c37fa 627 ((and qmark no-subst)
eab9ed67
RS
628 (y-or-n-p "Confirm--do you mean to use `?' as a wildcard? "))
629 (t))
630 (if on-each
631 (dired-bunch-files
632 (- 10000 (length command))
633 (function (lambda (&rest files)
634 (dired-run-shell-command
635 (dired-shell-stuff-it command files t arg))))
636 nil
637 file-list)
638 ;; execute the shell command
639 (dired-run-shell-command
640 (dired-shell-stuff-it command file-list nil arg))))))
dd87891b
RS
641
642;; Might use {,} for bash or csh:
643(defvar dired-mark-prefix ""
644 "Prepended to marked files in dired shell commands.")
645(defvar dired-mark-postfix ""
646 "Appended to marked files in dired shell commands.")
647(defvar dired-mark-separator " "
648 "Separates marked files in dired shell commands.")
649
06b60517 650(defun dired-shell-stuff-it (command file-list on-each &optional _raw-arg)
dd87891b
RS
651;; "Make up a shell command line from COMMAND and FILE-LIST.
652;; If ON-EACH is t, COMMAND should be applied to each file, else
653;; simply concat all files and apply COMMAND to this.
654;; FILE-LIST's elements will be quoted for the shell."
655;; Might be redefined for smarter things and could then use RAW-ARG
656;; (coming from interactive P and currently ignored) to decide what to do.
657;; Smart would be a way to access basename or extension of file names.
dd87891b 658 (let ((stuff-it
edb8d73e
FP
659 (if (or (string-match dired-star-subst-regexp command)
660 (string-match dired-quark-subst-regexp command))
661 (lambda (x)
662 (let ((retval command))
663 (while (string-match
664 "\\(^\\|[ \t]\\)\\([*?]\\)\\([ \t]\\|$\\)" retval)
665 (setq retval (replace-match x t t retval 2)))
666 retval))
667 (lambda (x) (concat command dired-mark-separator x)))))
dd87891b 668 (if on-each
9a79e9ae 669 (mapconcat stuff-it (mapcar 'shell-quote-argument file-list) ";")
eab9ed67
RS
670 (let ((files (mapconcat 'shell-quote-argument
671 file-list dired-mark-separator)))
dd87891b 672 (if (> (length file-list) 1)
eab9ed67
RS
673 (setq files (concat dired-mark-prefix files dired-mark-postfix)))
674 (funcall stuff-it files)))))
dd87891b
RS
675
676;; This is an extra function so that it can be redefined by ange-ftp.
05dcf18a 677;;;###autoload
6482fcac 678(defun dired-run-shell-command (command)
95ffcc7f
DL
679 (let ((handler
680 (find-file-name-handler (directory-file-name default-directory)
681 'shell-command)))
682 (if handler (apply handler 'shell-command (list command))
683 (shell-command command)))
6482fcac
RS
684 ;; Return nil for sake of nconc in dired-bunch-files.
685 nil)
83fadedf 686\f
dd87891b
RS
687
688(defun dired-check-process (msg program &rest arguments)
689; "Display MSG while running PROGRAM, and check for output.
690;Remaining arguments are strings passed as command arguments to PROGRAM.
691; On error, insert output
692; in a log buffer and return the offending ARGUMENTS or PROGRAM.
693; Caller can cons up a list of failed args.
694;Else returns nil for success."
695 (let (err-buffer err (dir default-directory))
696 (message "%s..." msg)
697 (save-excursion
698 ;; Get a clean buffer for error output:
699 (setq err-buffer (get-buffer-create " *dired-check-process output*"))
700 (set-buffer err-buffer)
701 (erase-buffer)
702 (setq default-directory dir ; caller's default-directory
4a725859 703 err (not (eq 0 (apply 'process-file program nil t nil arguments))))
dd87891b
RS
704 (if err
705 (progn
706 (dired-log (concat program " " (prin1-to-string arguments) "\n"))
707 (dired-log err-buffer)
708 (or arguments program t))
709 (kill-buffer err-buffer)
710 (message "%s...done" msg)
711 nil))))
83fadedf 712\f
dd87891b
RS
713;; Commands that delete or redisplay part of the dired buffer.
714
dd87891b 715(defun dired-kill-line (&optional arg)
d67f7e1f
LMI
716 "Kill the current line (not the files).
717With a prefix argument, kill that many lines starting with the current line.
718\(A negative argument kills backward.)"
dd87891b
RS
719 (interactive "P")
720 (setq arg (prefix-numeric-value arg))
721 (let (buffer-read-only file)
722 (while (/= 0 arg)
723 (setq file (dired-get-filename nil t))
724 (if (not file)
55535639 725 (error "Can only kill file lines")
dd87891b
RS
726 (save-excursion (and file
727 (dired-goto-subdir file)
728 (dired-kill-subdir)))
9b026d9f 729 (delete-region (line-beginning-position)
dd87891b
RS
730 (progn (forward-line 1) (point)))
731 (if (> arg 0)
732 (setq arg (1- arg))
733 (setq arg (1+ arg))
734 (forward-line -1))))
735 (dired-move-to-filename)))
736
737;;;###autoload
738(defun dired-do-kill-lines (&optional arg fmt)
739 "Kill all marked lines (not the files).
6482fcac 740With a prefix argument, kill that many lines starting with the current line.
769d9ed6
LT
741\(A negative argument kills backward.)
742If you use this command with a prefix argument to kill the line
743for a file that is a directory, which you have inserted in the
744Dired buffer as a subdirectory, then it deletes that subdirectory
745from the buffer as well.
746To kill an entire subdirectory \(without killing its line in the
747parent directory), go to its directory header line and use this
748command with a prefix argument (the value does not matter)."
dd87891b
RS
749 ;; Returns count of killed lines. FMT="" suppresses message.
750 (interactive "P")
6482fcac
RS
751 (if arg
752 (if (dired-get-subdir)
753 (dired-kill-subdir)
754 (dired-kill-line arg))
755 (save-excursion
756 (goto-char (point-min))
769d9ed6
LT
757 (let (buffer-read-only
758 (count 0)
759 (regexp (dired-marker-regexp)))
760 (while (and (not (eobp))
761 (re-search-forward regexp nil t))
762 (setq count (1+ count))
9b026d9f 763 (delete-region (line-beginning-position)
769d9ed6 764 (progn (forward-line 1) (point))))
6482fcac
RS
765 (or (equal "" fmt)
766 (message (or fmt "Killed %d line%s.") count (dired-plural-s count)))
767 count))))
dd87891b
RS
768
769;;;###end dired-cmd.el
83fadedf 770\f
dd87891b
RS
771;;; 30K
772;;;###begin dired-cp.el
773
774(defun dired-compress ()
775 ;; Compress or uncompress the current file.
776 ;; Return nil for success, offending filename else.
777 (let* (buffer-read-only
bfe81e78
RS
778 (from-file (dired-get-filename))
779 (new-file (dired-compress-file from-file)))
780 (if new-file
53a05194
RS
781 (let ((start (point)))
782 ;; Remove any preexisting entry for the name NEW-FILE.
783 (condition-case nil
784 (dired-remove-entry new-file)
785 (error nil))
786 (goto-char start)
787 ;; Now replace the current line with an entry for NEW-FILE.
788 (dired-update-file-line new-file) nil)
bfe81e78
RS
789 (dired-log (concat "Failed to compress" from-file))
790 from-file)))
791
077d5283
RS
792(defvar dired-compress-file-suffixes
793 '(("\\.gz\\'" "" "gunzip")
794 ("\\.tgz\\'" ".tar" "gunzip")
795 ("\\.Z\\'" "" "uncompress")
796 ;; For .z, try gunzip. It might be an old gzip file,
797 ;; or it might be from compact? pack? (which?) but gunzip handles both.
798 ("\\.z\\'" "" "gunzip")
999bd52a
JL
799 ("\\.dz\\'" "" "dictunzip")
800 ("\\.tbz\\'" ".tar" "bunzip2")
2d938ce7 801 ("\\.bz2\\'" "" "bunzip2")
470bce7d 802 ("\\.xz\\'" "" "unxz")
077d5283
RS
803 ;; This item controls naming for compression.
804 ("\\.tar\\'" ".tgz" nil))
805 "Control changes in file name suffixes for compression and uncompression.
806Each element specifies one transformation rule, and has the form:
807 (REGEXP NEW-SUFFIX PROGRAM)
808The rule applies when the old file name matches REGEXP.
809The new file name is computed by deleting the part that matches REGEXP
810 (as well as anything after that), then adding NEW-SUFFIX in its place.
811If PROGRAM is non-nil, the rule is an uncompression rule,
812and uncompression is done by running PROGRAM.
813Otherwise, the rule is a compression rule, and compression is done with gzip.")
814
d443f37c 815;;;###autoload
bfe81e78
RS
816(defun dired-compress-file (file)
817 ;; Compress or uncompress FILE.
818 ;; Return the name of the compressed or uncompressed file.
eb8c3be9 819 ;; Return nil if no change in files.
077d5283
RS
820 (let ((handler (find-file-name-handler file 'dired-compress-file))
821 suffix newname
822 (suffixes dired-compress-file-suffixes))
823 ;; See if any suffix rule matches this file name.
824 (while suffixes
825 (let (case-fold-search)
826 (if (string-match (car (car suffixes)) file)
827 (setq suffix (car suffixes) suffixes nil))
828 (setq suffixes (cdr suffixes))))
829 ;; If so, compute desired new name.
edb8d73e 830 (if suffix
077d5283
RS
831 (setq newname (concat (substring file 0 (match-beginning 0))
832 (nth 1 suffix))))
bfe81e78
RS
833 (cond (handler
834 (funcall handler 'dired-compress-file file))
835 ((file-symlink-p file)
836 nil)
077d5283
RS
837 ((and suffix (nth 2 suffix))
838 ;; We found an uncompression rule.
53a05194 839 (if (not (dired-check-process (concat "Uncompressing " file)
077d5283
RS
840 (nth 2 suffix) file))
841 newname))
dd87891b 842 (t
077d5283 843 ;;; We don't recognize the file as compressed, so compress it.
e251a1fd
RS
844 ;;; Try gzip; if we don't have that, use compress.
845 (condition-case nil
c8068734
CY
846 (let ((out-name (concat file ".gz")))
847 (and (or (not (file-exists-p out-name))
848 (y-or-n-p
9aea757b
CY
849 (format "File %s already exists. Really compress? "
850 out-name)))
c8068734
CY
851 (not (dired-check-process (concat "Compressing " file)
852 "gzip" "-f" file))
853 (or (file-exists-p out-name)
854 (setq out-name (concat file ".z")))
855 ;; Rename the compressed file to NEWNAME
856 ;; if it hasn't got that name already.
857 (if (and newname (not (equal newname out-name)))
858 (progn
859 (rename-file out-name newname t)
860 newname)
861 out-name)))
e251a1fd
RS
862 (file-error
863 (if (not (dired-check-process (concat "Compressing " file)
864 "compress" "-f" file))
077d5283 865 ;; Don't use NEWNAME with `compress'.
e251a1fd 866 (concat file ".Z"))))))))
83fadedf 867\f
dd87891b
RS
868(defun dired-mark-confirm (op-symbol arg)
869 ;; Request confirmation from the user that the operation described
870 ;; by OP-SYMBOL is to be performed on the marked files.
871 ;; Confirmation consists in a y-or-n question with a file list
872 ;; pop-up unless OP-SYMBOL is a member of `dired-no-confirm'.
873 ;; The files used are determined by ARG (as in dired-get-marked-files).
7baff557
SM
874 (or (eq dired-no-confirm t)
875 (memq op-symbol dired-no-confirm)
c232fd12
RS
876 ;; Pass t for DISTINGUISH-ONE-MARKED so that a single file which
877 ;; is marked pops up a window. That will help the user see
878 ;; it isn't the current line file.
879 (let ((files (dired-get-marked-files t arg nil t))
2de735de
RS
880 (string (if (eq op-symbol 'compress) "Compress or uncompress"
881 (capitalize (symbol-name op-symbol)))))
dd87891b 882 (dired-mark-pop-up nil op-symbol files (function y-or-n-p)
2de735de 883 (concat string " "
dd87891b
RS
884 (dired-mark-prompt arg files) "? ")))))
885
886(defun dired-map-over-marks-check (fun arg op-symbol &optional show-progress)
887; "Map FUN over marked files (with second ARG like in dired-map-over-marks)
888; and display failures.
889
890; FUN takes zero args. It returns non-nil (the offending object, e.g.
891; the short form of the filename) for a failure and probably logs a
892; detailed error explanation using function `dired-log'.
893
894; OP-SYMBOL is a symbol describing the operation performed (e.g.
895; `compress'). It is used with `dired-mark-pop-up' to prompt the user
896; (e.g. with `Compress * [2 files]? ') and to display errors (e.g.
897; `Failed to compress 1 of 2 files - type W to see why ("foo")')
898
899; SHOW-PROGRESS if non-nil means redisplay dired after each file."
900 (if (dired-mark-confirm op-symbol arg)
901 (let* ((total-list;; all of FUN's return values
902 (dired-map-over-marks (funcall fun) arg show-progress))
903 (total (length total-list))
904 (failures (delq nil total-list))
2de735de
RS
905 (count (length failures))
906 (string (if (eq op-symbol 'compress) "Compress or uncompress"
907 (capitalize (symbol-name op-symbol)))))
dd87891b
RS
908 (if (not failures)
909 (message "%s: %d file%s."
2de735de 910 string total (dired-plural-s total))
dd87891b
RS
911 ;; end this bunch of errors:
912 (dired-log-summary
913 (format "Failed to %s %d of %d file%s"
2de735de 914 (downcase string) count total (dired-plural-s total))
dd87891b
RS
915 failures)))))
916
05dcf18a 917;;;###autoload
3ef01959
CY
918(defun dired-query (sym prompt &rest args)
919 "Format PROMPT with ARGS, query user, and store the result in SYM.
920The return value is either nil or t.
921
922The user may type y or SPC to accept once; n or DEL to skip once;
923! to accept this and subsequent queries; or q or ESC to decline
924this and subsequent queries.
925
926If SYM is already bound to a non-nil value, this function may
927return automatically without querying the user. If SYM is !,
928return t; if SYM is q or ESC, return nil."
929 (let* ((char (symbol-value sym))
930 (char-choices '(?y ?\s ?n ?\177 ?! ?q ?\e)))
931 (cond ((eq char ?!)
932 t) ; accept, and don't ask again
933 ((memq char '(?q ?\e))
934 nil) ; skip, and don't ask again
935 (t ; no previous answer - ask now
936 (setq prompt
937 (concat (apply 'format prompt args)
938 (if help-form
939 (format " [Type yn!q or %s] "
6131ba7f 940 (key-description (vector help-char)))
3ef01959
CY
941 " [Type y, n, q or !] ")))
942 (set sym (setq char (read-char-choice prompt char-choices)))
943 (if (memq char '(?y ?\s ?!)) t)))))
944
83fadedf 945\f
dd87891b
RS
946;;;###autoload
947(defun dired-do-compress (&optional arg)
948 "Compress or uncompress marked (or next ARG) files."
949 (interactive "P")
950 (dired-map-over-marks-check (function dired-compress) arg 'compress t))
951
952;; Commands for Emacs Lisp files - load and byte compile
953
954(defun dired-byte-compile ()
955 ;; Return nil for success, offending file name else.
956 (let* ((filename (dired-get-filename))
123ec94d 957 elc-file buffer-read-only failure)
dd87891b
RS
958 (condition-case err
959 (save-excursion (byte-compile-file filename))
960 (error
961 (setq failure err)))
123ec94d 962 (setq elc-file (byte-compile-dest-file filename))
d5b876ef
RS
963 (or (file-exists-p elc-file)
964 (setq failure t))
dd87891b
RS
965 (if failure
966 (progn
967 (dired-log "Byte compile error for %s:\n%s\n" filename failure)
968 (dired-make-relative filename))
969 (dired-remove-file elc-file)
970 (forward-line) ; insert .elc after its .el file
971 (dired-add-file elc-file)
972 nil)))
973
974;;;###autoload
975(defun dired-do-byte-compile (&optional arg)
976 "Byte compile marked (or next ARG) Emacs Lisp files."
977 (interactive "P")
978 (dired-map-over-marks-check (function dired-byte-compile) arg 'byte-compile t))
979
980(defun dired-load ()
981 ;; Return nil for success, offending file name else.
982 (let ((file (dired-get-filename)) failure)
983 (condition-case err
984 (load file nil nil t)
985 (error (setq failure err)))
986 (if (not failure)
987 nil
988 (dired-log "Load error for %s:\n%s\n" file failure)
989 (dired-make-relative file))))
990
991;;;###autoload
992(defun dired-do-load (&optional arg)
993 "Load the marked (or next ARG) Emacs Lisp files."
994 (interactive "P")
995 (dired-map-over-marks-check (function dired-load) arg 'load t))
996
997;;;###autoload
998(defun dired-do-redisplay (&optional arg test-for-subdir)
999 "Redisplay all marked (or next ARG) files.
1000If on a subdir line, redisplay that subdirectory. In that case,
79d123ad
LT
1001a prefix arg lets you edit the `ls' switches used for the new listing.
1002
1003Dired remembers switches specified with a prefix arg, so that reverting
1004the buffer will not reset them. However, using `dired-undo' to re-insert
1005or delete subdirectories can bypass this machinery. Hence, you sometimes
1006may have to reset some subdirectory switches after a `dired-undo'.
1007You can reset all subdirectory switches to the default using
fad9e9b4 1008\\<dired-mode-map>\\[dired-reset-subdir-switches].
098c61f2 1009See Info node `(emacs)Subdir switches' for more details."
dd87891b
RS
1010 ;; Moves point if the next ARG files are redisplayed.
1011 (interactive "P\np")
1012 (if (and test-for-subdir (dired-get-subdir))
f2260f48
LT
1013 (let* ((dir (dired-get-subdir))
1014 (switches (cdr (assoc-string dir dired-switches-alist))))
1015 (dired-insert-subdir
1016 dir
1017 (when arg
1018 (read-string "Switches for listing: "
1019 (or switches
1020 dired-subdir-switches
1021 dired-actual-switches)))))
dd87891b
RS
1022 (message "Redisplaying...")
1023 ;; message much faster than making dired-map-over-marks show progress
00aa3651
RS
1024 (dired-uncache
1025 (if (consp dired-directory) (car dired-directory) dired-directory))
86a6e8e0 1026 (dired-map-over-marks (let ((fname (dired-get-filename))
9173deec 1027 ;; Postpone readin hook till we map
86a6e8e0
LL
1028 ;; over all marked files (Bug#6810).
1029 (dired-after-readin-hook nil))
dd87891b
RS
1030 (message "Redisplaying... %s" fname)
1031 (dired-update-file-line fname))
1032 arg)
86a6e8e0 1033 (run-hooks 'dired-after-readin-hook)
dd87891b
RS
1034 (dired-move-to-filename)
1035 (message "Redisplaying...done")))
79d123ad
LT
1036
1037(defun dired-reset-subdir-switches ()
1038 "Set `dired-switches-alist' to nil and revert dired buffer."
1039 (interactive)
1040 (setq dired-switches-alist nil)
1041 (revert-buffer))
83fadedf 1042\f
dd87891b
RS
1043(defun dired-update-file-line (file)
1044 ;; Delete the current line, and insert an entry for FILE.
1045 ;; If FILE is nil, then just delete the current line.
1046 ;; Keeps any marks that may be present in column one (doing this
1047 ;; here is faster than with dired-add-entry's optional arg).
1048 ;; Does not update other dired buffers. Use dired-relist-entry for that.
edb57480
SB
1049 (let* ((opoint (line-beginning-position))
1050 (char (char-after opoint))
1051 (buffer-read-only))
9b026d9f 1052 (delete-region opoint (progn (forward-line 1) (point)))
dd87891b
RS
1053 (if file
1054 (progn
24193f35 1055 (dired-add-entry file nil t)
dd87891b
RS
1056 ;; Replace space by old marker without moving point.
1057 ;; Faster than goto+insdel inside a save-excursion?
1058 (subst-char-in-region opoint (1+ opoint) ?\040 char))))
1059 (dired-move-to-filename))
1060
d443f37c 1061;;;###autoload
dd87891b
RS
1062(defun dired-add-file (filename &optional marker-char)
1063 (dired-fun-in-all-buffers
b2a59df0 1064 (file-name-directory filename) (file-name-nondirectory filename)
dd87891b
RS
1065 (function dired-add-entry) filename marker-char))
1066
30abce25
GM
1067(defvar dired-omit-mode)
1068(declare-function dired-omit-regexp "dired-x" ())
1069(defvar dired-omit-localp)
1070
24193f35 1071(defun dired-add-entry (filename &optional marker-char relative)
30abce25
GM
1072 "Add a new dired entry for FILENAME.
1073Optionally mark it with MARKER-CHAR (a character, else uses
1074`dired-marker-char'). Note that this adds the entry `out of order'
1075if files are sorted by time, etc.
1076Skips files that match `dired-trivial-filenames'.
1077Exposes hidden subdirectories if a file is added there.
1078
1079If `dired-x' is loaded and `dired-omit-mode' is enabled, skips
1080files matching `dired-omit-regexp'."
1081 (if (or (not (featurep 'dired-x))
1082 (not dired-omit-mode)
1083 ;; Avoid calling ls for files that are going to be omitted anyway.
1084 (let ((omit-re (dired-omit-regexp)))
1085 (or (string= omit-re "")
1086 (not (string-match omit-re
1087 (cond
1088 ((eq 'no-dir dired-omit-localp)
1089 filename)
1090 ((eq t dired-omit-localp)
1091 (dired-make-relative filename))
1092 (t
1093 (dired-make-absolute
1094 filename
1095 (file-name-directory filename)))))))))
1096 ;; Do it!
1097 (progn
1098 (setq filename (directory-file-name filename))
1099 ;; Entry is always for files, even if they happen to also be directories
1100 (let* ((opoint (point))
1101 (cur-dir (dired-current-directory))
30abce25
GM
1102 (directory (if relative cur-dir (file-name-directory filename)))
1103 reason)
1104 (setq filename
1105 (if relative
1106 (file-relative-name filename directory)
1107 (file-name-nondirectory filename))
1108 reason
1109 (catch 'not-found
1110 (if (string= directory cur-dir)
1111 (progn
1112 (skip-chars-forward "^\r\n")
1113 (if (eq (following-char) ?\r)
1114 (dired-unhide-subdir))
1115 ;; We are already where we should be, except when
1116 ;; point is before the subdir line or its total line.
1117 (let ((p (dired-after-subdir-garbage cur-dir)))
1118 (if (< (point) p)
1119 (goto-char p))))
1120 ;; else try to find correct place to insert
1121 (if (dired-goto-subdir directory)
1122 (progn ;; unhide if necessary
1123 (if (looking-at "\r")
1124 ;; Point is at end of subdir line.
1125 (dired-unhide-subdir))
1126 ;; found - skip subdir and `total' line
1127 ;; and uninteresting files like . and ..
1128 ;; This better not move into the next subdir!
1129 (dired-goto-next-nontrivial-file))
1130 ;; not found
1131 (throw 'not-found "Subdir not found")))
1132 (let (buffer-read-only opoint)
1133 (beginning-of-line)
1134 (setq opoint (point))
1135 ;; Don't expand `.'.
1136 ;; Show just the file name within directory.
1137 (let ((default-directory directory))
1138 (dired-insert-directory
1139 directory
1140 (concat dired-actual-switches " -d")
1141 (list filename)))
1142 (goto-char opoint)
1143 ;; Put in desired marker char.
1144 (when marker-char
1145 (let ((dired-marker-char
1146 (if (integerp marker-char) marker-char
1147 dired-marker-char)))
1148 (dired-mark nil)))
1149 ;; Compensate for a bug in ange-ftp.
1150 ;; It inserts the file's absolute name, rather than
1151 ;; the relative one. That may be hard to fix since it
1152 ;; is probably controlled by something in ftp.
1153 (goto-char opoint)
1154 (let ((inserted-name (dired-get-filename 'verbatim)))
1155 (if (file-name-directory inserted-name)
1156 (let (props)
1157 (end-of-line)
1158 (forward-char (- (length inserted-name)))
1159 (setq props (text-properties-at (point)))
1160 (delete-char (length inserted-name))
1161 (let ((pt (point)))
1162 (insert filename)
1163 (set-text-properties pt (point) props))
1164 (forward-char 1))
1165 (forward-line 1)))
1166 (forward-line -1)
1167 (if dired-after-readin-hook
1168 ;; The subdir-alist is not affected...
1169 (save-excursion ; ...so we can run it right now:
1170 (save-restriction
1171 (beginning-of-line)
1172 (narrow-to-region (point)
1173 (line-beginning-position 2))
1174 (run-hooks 'dired-after-readin-hook))))
1175 (dired-move-to-filename))
1176 ;; return nil if all went well
1177 nil))
1178 (if reason ; don't move away on failure
1179 (goto-char opoint))
1180 (not reason))) ; return t on success, nil else
1181 ;; Don't do it (dired-omit-mode).
1182 ;; Return t for success (perhaps we should return file-exists-p).
1183 t))
dd87891b 1184
dd87891b
RS
1185(defun dired-after-subdir-garbage (dir)
1186 ;; Return pos of first file line of DIR, skipping header and total
1187 ;; or wildcard lines.
1188 ;; Important: never moves into the next subdir.
1189 ;; DIR is assumed to be unhidden.
dd87891b
RS
1190 (save-excursion
1191 (or (dired-goto-subdir dir) (error "This cannot happen"))
1192 (forward-line 1)
1193 (while (and (not (eolp)) ; don't cross subdir boundary
1194 (not (dired-move-to-filename)))
1195 (forward-line 1))
1196 (point)))
1197
d443f37c 1198;;;###autoload
dd87891b
RS
1199(defun dired-remove-file (file)
1200 (dired-fun-in-all-buffers
b2a59df0
RS
1201 (file-name-directory file) (file-name-nondirectory file)
1202 (function dired-remove-entry) file))
dd87891b
RS
1203
1204(defun dired-remove-entry (file)
1205 (save-excursion
1206 (and (dired-goto-file file)
1207 (let (buffer-read-only)
1208 (delete-region (progn (beginning-of-line) (point))
9b026d9f 1209 (line-beginning-position 2))))))
dd87891b 1210
d443f37c 1211;;;###autoload
dd87891b 1212(defun dired-relist-file (file)
e5369aad 1213 "Create or update the line for FILE in all Dired buffers it would belong in."
dd87891b 1214 (dired-fun-in-all-buffers (file-name-directory file)
b2a59df0 1215 (file-name-nondirectory file)
dd87891b
RS
1216 (function dired-relist-entry) file))
1217
1218(defun dired-relist-entry (file)
1219 ;; Relist the line for FILE, or just add it if it did not exist.
57dabf6b 1220 ;; FILE must be an absolute file name.
dd87891b
RS
1221 (let (buffer-read-only marker)
1222 ;; If cursor is already on FILE's line delete-region will cause
1223 ;; save-excursion to fail because of floating makers,
1224 ;; moving point to beginning of line. Sigh.
1225 (save-excursion
1226 (and (dired-goto-file file)
1227 (delete-region (progn (beginning-of-line)
1228 (setq marker (following-char))
1229 (point))
9b026d9f 1230 (line-beginning-position 2)))
dd87891b
RS
1231 (setq file (directory-file-name file))
1232 (dired-add-entry file (if (eq ?\040 marker) nil marker)))))
83fadedf 1233\f
dd87891b
RS
1234;;; Copy, move/rename, making hard and symbolic links
1235
91a7e829 1236(defcustom dired-backup-overwrite nil
9201cc28 1237 "Non-nil if Dired should ask about making backups before overwriting files.
91a7e829
RS
1238Special value `always' suppresses confirmation."
1239 :type '(choice (const :tag "off" nil)
1240 (const :tag "suppress" always)
a9e9b8fa 1241 (other :tag "ask" t))
91a7e829 1242 :group 'dired)
dd87891b 1243
bf0de14d
CY
1244;; This is a fluid var used in dired-handle-overwrite. It should be
1245;; let-bound whenever dired-copy-file etc are called. See
1246;; dired-create-files for an example.
1247(defvar dired-overwrite-confirmed)
6482fcac 1248
dd87891b 1249(defun dired-handle-overwrite (to)
e5369aad 1250 ;; Save old version of file TO that is to be overwritten.
6482fcac 1251 ;; `dired-overwrite-confirmed' and `overwrite-backup-query' are fluid vars
dd87891b 1252 ;; from dired-create-files.
d63a6ae0 1253 (let (backup)
bbfe2308
CY
1254 (when (and dired-backup-overwrite
1255 dired-overwrite-confirmed
1256 (setq backup (car (find-backup-file-name to)))
1257 (or (eq 'always dired-backup-overwrite)
1258 (dired-query 'overwrite-backup-query
1259 "Make backup for existing file `%s'? "
1260 to)))
1261 (rename-file to backup 0) ; confirm overwrite of old backup
1262 (dired-relist-entry backup))))
dd87891b 1263
d443f37c 1264;;;###autoload
dd87891b
RS
1265(defun dired-copy-file (from to ok-flag)
1266 (dired-handle-overwrite to)
c62a8073
RS
1267 (dired-copy-file-recursive from to ok-flag dired-copy-preserve-time t
1268 dired-recursive-copies))
dd87891b 1269
8e845e23
JB
1270(declare-function make-symbolic-link "fileio.c")
1271
ba1acd68
RS
1272(defun dired-copy-file-recursive (from to ok-flag &optional
1273 preserve-time top recursive)
40311efc 1274 (when (and (eq t (car (file-attributes from)))
42ee526b 1275 (file-in-directory-p to from))
25b2e303 1276 (error "Cannot copy `%s' into its subdirectory `%s'" from to))
06b60517 1277 (let ((attrs (file-attributes from)))
3b68c506
RS
1278 (if (and recursive
1279 (eq t (car attrs))
1280 (or (eq recursive 'always)
ce5a3ac0 1281 (yes-or-no-p (format "Recursive copies of %s? " from))))
3b68c506 1282 ;; This is a directory.
06b60517 1283 (copy-directory from to preserve-time)
3b68c506
RS
1284 ;; Not a directory.
1285 (or top (dired-handle-overwrite to))
c62a8073
RS
1286 (condition-case err
1287 (if (stringp (car attrs))
1288 ;; It is a symlink
1289 (make-symbolic-link (car attrs) to ok-flag)
06b60517 1290 (copy-file from to ok-flag preserve-time))
4a725859 1291 (file-date-error
c62a8073
RS
1292 (push (dired-make-relative from)
1293 dired-create-files-failures)
7a547817 1294 (dired-log "Can't set date on %s:\n%s\n" from err))))))
ba1acd68 1295
d443f37c 1296;;;###autoload
e5369aad
RS
1297(defun dired-rename-file (file newname ok-if-already-exists)
1298 (dired-handle-overwrite newname)
1299 (rename-file file newname ok-if-already-exists) ; error is caught in -create-files
dd87891b 1300 ;; Silently rename the visited file of any buffer visiting this file.
e5369aad
RS
1301 (and (get-file-buffer file)
1302 (with-current-buffer (get-file-buffer file)
1303 (set-visited-file-name newname nil t)))
1304 (dired-remove-file file)
dd87891b 1305 ;; See if it's an inserted subdir, and rename that, too.
e5369aad 1306 (dired-rename-subdir file newname))
dd87891b
RS
1307
1308(defun dired-rename-subdir (from-dir to-dir)
1309 (setq from-dir (file-name-as-directory from-dir)
1310 to-dir (file-name-as-directory to-dir))
b2a59df0 1311 (dired-fun-in-all-buffers from-dir nil
dd87891b
RS
1312 (function dired-rename-subdir-1) from-dir to-dir)
1313 ;; Update visited file name of all affected buffers
9df38cef
RS
1314 (let ((expanded-from-dir (expand-file-name from-dir))
1315 (blist (buffer-list)))
dd87891b 1316 (while blist
7fdbcd83 1317 (with-current-buffer (car blist)
dd87891b 1318 (if (and buffer-file-name
9df38cef 1319 (dired-in-this-tree buffer-file-name expanded-from-dir))
dd87891b 1320 (let ((modflag (buffer-modified-p))
83fadedf 1321 (to-file (dired-replace-in-string
dd87891b
RS
1322 (concat "^" (regexp-quote from-dir))
1323 to-dir
1324 buffer-file-name)))
1325 (set-visited-file-name to-file)
1326 (set-buffer-modified-p modflag))))
1327 (setq blist (cdr blist)))))
1328
1329(defun dired-rename-subdir-1 (dir to)
1330 ;; Rename DIR to TO in headerlines and dired-subdir-alist, if DIR or
1331 ;; one of its subdirectories is expanded in this buffer.
9df38cef
RS
1332 (let ((expanded-dir (expand-file-name dir))
1333 (alist dired-subdir-alist)
dd87891b
RS
1334 (elt nil))
1335 (while alist
1336 (setq elt (car alist)
1337 alist (cdr alist))
9df38cef 1338 (if (dired-in-this-tree (car elt) expanded-dir)
dd87891b
RS
1339 ;; ELT's subdir is affected by the rename
1340 (dired-rename-subdir-2 elt dir to)))
1341 (if (equal dir default-directory)
1342 ;; if top level directory was renamed, lots of things have to be
1343 ;; updated:
1344 (progn
1345 (dired-unadvertise dir) ; we no longer dired DIR...
1346 (setq default-directory to
1347 dired-directory (expand-file-name;; this is correct
1348 ;; with and without wildcards
1349 (file-name-nondirectory dired-directory)
1350 to))
1351 (let ((new-name (file-name-nondirectory
1352 (directory-file-name dired-directory))))
1353 ;; try to rename buffer, but just leave old name if new
1354 ;; name would already exist (don't try appending "<%d>")
1355 (or (get-buffer new-name)
1356 (rename-buffer new-name)))
1357 ;; ... we dired TO now:
1358 (dired-advertise)))))
1359
1360(defun dired-rename-subdir-2 (elt dir to)
f2260f48
LT
1361 ;; Update the headerline and dired-subdir-alist element, as well as
1362 ;; dired-switches-alist element, of directory described by
1363 ;; alist-element ELT to reflect the moving of DIR to TO. Thus, ELT
1364 ;; describes either DIR itself or a subdir of DIR.
dd87891b
RS
1365 (save-excursion
1366 (let ((regexp (regexp-quote (directory-file-name dir)))
1367 (newtext (directory-file-name to))
1368 buffer-read-only)
1369 (goto-char (dired-get-subdir-min elt))
1370 ;; Update subdir headerline in buffer
1371 (if (not (looking-at dired-subdir-regexp))
1372 (error "%s not found where expected - dired-subdir-alist broken?"
1373 dir)
1374 (goto-char (match-beginning 1))
1375 (if (re-search-forward regexp (match-end 1) t)
1376 (replace-match newtext t t)
1377 (error "Expected to find `%s' in headerline of %s" dir (car elt))))
f2260f48
LT
1378 ;; Update buffer-local dired-subdir-alist and dired-switches-alist
1379 (let ((cons (assoc-string (car elt) dired-switches-alist))
1380 (cur-dir (dired-normalize-subdir
1381 (dired-replace-in-string regexp newtext (car elt)))))
1382 (setcar elt cur-dir)
1383 (when cons (setcar cons cur-dir))))))
83fadedf 1384\f
06b60517
JB
1385;; Bound in dired-create-files
1386(defvar overwrite-query)
1387(defvar overwrite-backup-query)
1388
dd87891b
RS
1389;; The basic function for half a dozen variations on cp/mv/ln/ln -s.
1390(defun dired-create-files (file-creator operation fn-list name-constructor
1391 &optional marker-char)
0d9e9a12
CY
1392 "Create one or more new files from a list of existing files FN-LIST.
1393This function also handles querying the user, updating Dired
1394buffers, and displaying a success or failure message.
dd87891b 1395
0d9e9a12
CY
1396FILE-CREATOR should be a function. It is called once for each
1397file in FN-LIST, and must create a new file, querying the user
1398and updating Dired buffers as necessary. It should accept three
1399arguments: the old file name, the new name, and an argument
1400OK-IF-ALREADY-EXISTS with the same meaning as in `copy-file'.
dd87891b 1401
0d9e9a12
CY
1402OPERATION should be a capitalized string describing the operation
1403performed (e.g. `Copy'). It is used for error logging.
dd87891b 1404
0d9e9a12 1405FN-LIST is the list of files to copy (full absolute file names).
dd87891b 1406
0d9e9a12
CY
1407NAME-CONSTRUCTOR should be a function accepting a single
1408argument, the name of an old file, and returning either the
1409corresponding new file name or nil to skip.
dd87891b 1410
0d9e9a12
CY
1411Optional MARKER-CHAR is a character with which to mark every
1412newfile's entry, or t to use the current marker character if the
1413old file was marked."
c62a8073
RS
1414 (let (dired-create-files-failures failures
1415 skipped (success-count 0) (total (length fn-list)))
dd87891b
RS
1416 (let (to overwrite-query
1417 overwrite-backup-query) ; for dired-handle-overwrite
04509548
SM
1418 (dolist (from fn-list)
1419 (setq to (funcall name-constructor from))
1420 (if (equal to from)
1421 (progn
1422 (setq to nil)
1423 (dired-log "Cannot %s to same file: %s\n"
1424 (downcase operation) from)))
1425 (if (not to)
1426 (setq skipped (cons (dired-make-relative from) skipped))
1427 (let* ((overwrite (file-exists-p to))
1428 (dired-overwrite-confirmed ; for dired-handle-overwrite
1429 (and overwrite
1430 (let ((help-form '(format "\
dd87891b
RS
1431Type SPC or `y' to overwrite file `%s',
1432DEL or `n' to skip to next,
1433ESC or `q' to not overwrite any of the remaining files,
1434`!' to overwrite all remaining files with no more questions." to)))
04509548
SM
1435 (dired-query 'overwrite-query
1436 "Overwrite `%s'?" to))))
1437 ;; must determine if FROM is marked before file-creator
1438 ;; gets a chance to delete it (in case of a move).
1439 (actual-marker-char
1440 (cond ((integerp marker-char) marker-char)
1441 (marker-char (dired-file-marker from)) ; slow
1442 (t nil))))
25b2e303 1443 ;; Handle the `dired-copy-file' file-creator specially
1444 ;; When copying a directory to another directory or
1445 ;; possibly to itself or one of its subdirectories.
1446 ;; e.g "~/foo/" => "~/test/"
1447 ;; or "~/foo/" =>"~/foo/"
1448 ;; or "~/foo/ => ~/foo/bar/")
1449 ;; In this case the 'name-constructor' have set the destination
1450 ;; TO to "~/test/foo" because the old emacs23 behavior
1451 ;; of `copy-directory' was to not create the subdirectory
1452 ;; and instead copy the contents.
1453 ;; With the new behavior of `copy-directory'
1454 ;; (similar to the `cp' shell command) we don't
1455 ;; need such a construction of the target directory,
1456 ;; so modify the destination TO to "~/test/" instead of "~/test/foo/".
1457 (let ((destname (file-name-directory to)))
1458 (when (and (file-directory-p from)
1459 (file-directory-p to)
1460 (eq file-creator 'dired-copy-file))
1461 (setq to destname))
40311efc
TV
1462 ;; If DESTNAME is a subdirectory of FROM, not a symlink,
1463 ;; and the method in use is copying, signal an error.
1464 (and (eq t (car (file-attributes destname)))
1465 (eq file-creator 'dired-copy-file)
42ee526b 1466 (file-in-directory-p destname from)
7d0c323f 1467 (error "Cannot copy `%s' into its subdirectory `%s'"
40311efc 1468 from to)))
04509548
SM
1469 (condition-case err
1470 (progn
1471 (funcall file-creator from to dired-overwrite-confirmed)
1472 (if overwrite
1473 ;; If we get here, file-creator hasn't been aborted
1474 ;; and the old entry (if any) has to be deleted
1475 ;; before adding the new entry.
1476 (dired-remove-file to))
1477 (setq success-count (1+ success-count))
1478 (message "%s: %d of %d" operation success-count total)
1479 (dired-add-file to actual-marker-char))
1480 (file-error ; FILE-CREATOR aborted
1481 (progn
1482 (push (dired-make-relative from)
1483 failures)
1484 (dired-log "%s `%s' to `%s' failed:\n%s\n"
1485 operation from to err))))))))
dd87891b 1486 (cond
c62a8073
RS
1487 (dired-create-files-failures
1488 (setq failures (nconc failures dired-create-files-failures))
1489 (dired-log-summary
1490 (format "%s failed for %d file%s in %d requests"
1491 operation (length failures)
1492 (dired-plural-s (length failures))
1493 total)
1494 failures))
dd87891b
RS
1495 (failures
1496 (dired-log-summary
1497 (format "%s failed for %d of %d file%s"
c62a8073
RS
1498 operation (length failures)
1499 total (dired-plural-s total))
dd87891b
RS
1500 failures))
1501 (skipped
1502 (dired-log-summary
1503 (format "%s: %d of %d file%s skipped"
1504 operation (length skipped) total
1505 (dired-plural-s total))
1506 skipped))
1507 (t
1508 (message "%s: %s file%s"
1509 operation success-count (dired-plural-s success-count)))))
1510 (dired-move-to-filename))
83fadedf 1511\f
dd87891b 1512(defun dired-do-create-files (op-symbol file-creator operation arg
616e14f4
SM
1513 &optional marker-char op1
1514 how-to)
1515 "Create a new file for each marked file.
1516Prompts user for target, which is a directory in which to create
9c8f194d 1517 the new files. Target may also be a plain file if only one marked
dcaf31d3
EZ
1518 file exists. The way the default for the target directory is
1519 computed depends on the value of `dired-dwim-target-directory'.
616e14f4
SM
1520OP-SYMBOL is the symbol for the operation. Function `dired-mark-pop-up'
1521 will determine whether pop-ups are appropriate for this OP-SYMBOL.
1522FILE-CREATOR and OPERATION as in `dired-create-files'.
1523ARG as in `dired-get-marked-files'.
1524Optional arg MARKER-CHAR as in `dired-create-files'.
1525Optional arg OP1 is an alternate form for OPERATION if there is
1526 only one file.
4c36be58 1527Optional arg HOW-TO determines how to treat the target.
9c8f194d
CY
1528 If HOW-TO is nil, use `file-directory-p' to determine if the
1529 target is a directory. If so, the marked file(s) are created
1530 inside that directory. Otherwise, the target is a plain file;
1531 an error is raised unless there is exactly one marked file.
1532 If HOW-TO is t, target is always treated as a plain file.
1533 Otherwise, HOW-TO should be a function of one argument, TARGET.
1534 If its return value is nil, TARGET is regarded as a plain file.
1535 If it return value is a list, TARGET is a generalized
1536 directory (e.g. some sort of archive). The first element of
1537 this list must be a function with at least four arguments:
1538 operation - as OPERATION above.
1539 rfn-list - list of the relative names for the marked files.
1540 fn-list - list of the absolute names for the marked files.
1541 target - the name of the target itself.
616e14f4 1542 The rest of into-dir are optional arguments.
9c8f194d 1543 For any other return value, TARGET is treated as a directory."
dd87891b
RS
1544 (or op1 (setq op1 operation))
1545 (let* ((fn-list (dired-get-marked-files nil arg))
ba1acd68
RS
1546 (rfn-list (mapcar (function dired-make-relative) fn-list))
1547 (dired-one-file ; fluid variable inside dired-create-files
1548 (and (consp fn-list) (null (cdr fn-list)) (car fn-list)))
75ab0c79
GM
1549 (target-dir (dired-dwim-target-directory))
1550 (default (and dired-one-file
1551 (expand-file-name (file-name-nondirectory (car fn-list))
1552 target-dir)))
e237085f 1553 (defaults (dired-dwim-target-defaults fn-list target-dir))
ba1acd68 1554 (target (expand-file-name ; fluid variable inside dired-create-files
e237085f
JL
1555 (minibuffer-with-setup-hook
1556 (lambda ()
1557 (set (make-local-variable 'minibuffer-default-add-function) nil)
1558 (setq minibuffer-default defaults))
1559 (dired-mark-read-file-name
1560 (concat (if dired-one-file op1 operation) " %s to: ")
1561 target-dir op-symbol arg rfn-list default))))
325fec3c
EZ
1562 (into-dir (cond ((null how-to)
1563 ;; Allow DOS/Windows users to change the letter
1564 ;; case of a directory. If we don't test these
1565 ;; conditions up front, file-directory-p below
1566 ;; will return t because the filesystem is
1567 ;; case-insensitive, and Emacs will try to move
1568 ;; foo -> foo/foo, which fails.
c60ee5e7 1569 (if (and (memq system-type '(ms-dos windows-nt cygwin))
325fec3c
EZ
1570 (eq op-symbol 'move)
1571 dired-one-file
1572 (string= (downcase
1573 (expand-file-name (car fn-list)))
1574 (downcase
1575 (expand-file-name target)))
1576 (not (string=
1577 (file-name-nondirectory (car fn-list))
1578 (file-name-nondirectory target))))
1579 nil
1580 (file-directory-p target)))
dd87891b
RS
1581 ((eq how-to t) nil)
1582 (t (funcall how-to target)))))
ba1acd68
RS
1583 (if (and (consp into-dir) (functionp (car into-dir)))
1584 (apply (car into-dir) operation rfn-list fn-list target (cdr into-dir))
1585 (if (not (or dired-one-file into-dir))
1586 (error "Marked %s: target must be a directory: %s" operation target))
1587 ;; rename-file bombs when moving directories unless we do this:
1588 (or into-dir (setq target (directory-file-name target)))
1589 (dired-create-files
1590 file-creator operation fn-list
1591 (if into-dir ; target is a directory
1592 ;; This function uses fluid variable target when called
1593 ;; inside dired-create-files:
1594 (function
1595 (lambda (from)
1596 (expand-file-name (file-name-nondirectory from) target)))
06b60517 1597 (function (lambda (_from) target)))
ba1acd68 1598 marker-char))))
dd87891b
RS
1599
1600;; Read arguments for a marked-files command that wants a file name,
1601;; perhaps popping up the list of marked files.
1602;; ARG is the prefix arg and indicates whether the files came from
1603;; marks (ARG=nil) or a repeat factor (integerp ARG).
1604;; If the current file was used, the list has but one element and ARG
1605;; does not matter. (It is non-nil, non-integer in that case, namely '(4)).
64666d2d
MB
1606;; DEFAULT is the default value to return if the user just hits RET;
1607;; if it is omitted or nil, then the name of the directory is used.
dd87891b 1608
64666d2d
MB
1609(defun dired-mark-read-file-name (prompt dir op-symbol arg files
1610 &optional default)
dd87891b
RS
1611 (dired-mark-pop-up
1612 nil op-symbol files
1613 (function read-file-name)
64666d2d 1614 (format prompt (dired-mark-prompt arg files)) dir default))
dd87891b
RS
1615
1616(defun dired-dwim-target-directory ()
1617 ;; Try to guess which target directory the user may want.
e237085f
JL
1618 ;; If there is a dired buffer displayed in one of the next windows,
1619 ;; use its current subdir, else use current subdir of this dired buffer.
dd87891b
RS
1620 (let ((this-dir (and (eq major-mode 'dired-mode)
1621 (dired-current-directory))))
1622 ;; non-dired buffer may want to profit from this function, e.g. vm-uudecode
1623 (if dired-dwim-target
e237085f
JL
1624 (let* ((other-win (get-window-with-predicate
1625 (lambda (window)
1626 (with-current-buffer (window-buffer window)
1627 (eq major-mode 'dired-mode)))))
1628 (other-dir (and other-win
1629 (with-current-buffer (window-buffer other-win)
1630 (and (eq major-mode 'dired-mode)
1631 (dired-current-directory))))))
dd87891b
RS
1632 (or other-dir this-dir))
1633 this-dir)))
e237085f
JL
1634
1635(defun dired-dwim-target-defaults (fn-list target-dir)
1636 ;; Return a list of default values for file-reading functions in Dired.
1637 ;; This list may contain directories from Dired buffers in other windows.
1638 ;; `fn-list' is a list of file names used to build a list of defaults.
1639 ;; When nil or more than one element, a list of defaults will
1640 ;; contain only directory names. `target-dir' is a directory name
1641 ;; to exclude from the returned list, for the case when this
1642 ;; directory name is already presented in initial input.
1643 ;; For Dired operations that support `dired-dwim-target',
1644 ;; the argument `target-dir' should have the value returned
1645 ;; from `dired-dwim-target-directory'.
1646 (let ((dired-one-file
1647 (and (consp fn-list) (null (cdr fn-list)) (car fn-list)))
1648 (current-dir (and (eq major-mode 'dired-mode)
1649 (dired-current-directory)))
1650 dired-dirs)
1651 ;; Get a list of directories of visible buffers in dired-mode.
1652 (walk-windows (lambda (w)
1653 (with-current-buffer (window-buffer w)
1654 (and (eq major-mode 'dired-mode)
1655 (push (dired-current-directory) dired-dirs)))))
1656 ;; Force the current dir to be the first in the list.
1657 (setq dired-dirs
1658 (delete-dups (delq nil (cons current-dir (nreverse dired-dirs)))))
1659 ;; Remove the target dir (if specified) or the current dir from
1660 ;; default values, because it should be already in initial input.
1661 (setq dired-dirs (delete (or target-dir current-dir) dired-dirs))
1662 ;; Return a list of default values.
1663 (if dired-one-file
1664 ;; For one file operation, provide a list that contains
1665 ;; other directories, other directories with the appended filename
1666 ;; and the current directory with the appended filename, e.g.
1667 ;; 1. /TARGET-DIR/
1668 ;; 2. /TARGET-DIR/FILENAME
1669 ;; 3. /CURRENT-DIR/FILENAME
1670 (append dired-dirs
1671 (mapcar (lambda (dir)
1672 (expand-file-name
1673 (file-name-nondirectory (car fn-list)) dir))
1674 (reverse dired-dirs))
1675 (list (expand-file-name
1676 (file-name-nondirectory (car fn-list))
1677 (or target-dir current-dir))))
1678 ;; For multi-file operation, return only a list of other directories.
1679 dired-dirs)))
1680
83fadedf 1681\f
dd87891b
RS
1682;;;###autoload
1683(defun dired-create-directory (directory)
ff854b0b
CY
1684 "Create a directory called DIRECTORY.
1685If DIRECTORY already exists, signal an error."
dd87891b
RS
1686 (interactive
1687 (list (read-file-name "Create directory: " (dired-current-directory))))
934b4968
JL
1688 (let* ((expanded (directory-file-name (expand-file-name directory)))
1689 (try expanded) new)
ff854b0b
CY
1690 (if (file-exists-p expanded)
1691 (error "Cannot create directory %s: file exists" expanded))
934b4968
JL
1692 ;; Find the topmost nonexistent parent dir (variable `new')
1693 (while (and try (not (file-exists-p try)) (not (equal new try)))
1694 (setq new try
1695 try (directory-file-name (file-name-directory try))))
1696 (make-directory expanded t)
1697 (when new
1698 (dired-add-file new)
1699 (dired-move-to-filename))))
dd87891b
RS
1700
1701(defun dired-into-dir-with-symlinks (target)
1702 (and (file-directory-p target)
1703 (not (file-symlink-p target))))
1704;; This may not always be what you want, especially if target is your
1705;; home directory and it happens to be a symbolic link, as is often the
1706;; case with NFS and automounters. Or if you want to make symlinks
1707;; into directories that themselves are only symlinks, also quite
1708;; common.
1709
1710;; So we don't use this function as value for HOW-TO in
1711;; dired-do-symlink, which has the minor disadvantage of
1712;; making links *into* a symlinked-dir, when you really wanted to
1713;; *overwrite* that symlink. In that (rare, I guess) case, you'll
1714;; just have to remove that symlink by hand before making your marked
1715;; symlinks.
1716
ba1acd68 1717(defvar dired-copy-how-to-fn nil
5a0c3f56 1718 "Either nil or a function used by `dired-do-copy' to determine target.
ba1acd68
RS
1719See HOW-TO argument for `dired-do-create-files'.")
1720
dd87891b
RS
1721;;;###autoload
1722(defun dired-do-copy (&optional arg)
1723 "Copy all marked (or next ARG) files, or copy the current file.
1724This normally preserves the last-modified date when copying.
1725When operating on just the current file, you specify the new name.
b5458fc2
RS
1726When operating on multiple or marked files, you specify a directory,
1727and new copies of these files are made in that directory
dcaf31d3
EZ
1728with the same names that the files currently have. The default
1729suggested for the target directory depends on the value of
ec9581d5
RS
1730`dired-dwim-target', which see.
1731
1732This command copies symbolic links by creating new ones,
1733like `cp -d'."
dd87891b 1734 (interactive "P")
ea185644 1735 (let ((dired-recursive-copies dired-recursive-copies))
ba1acd68 1736 (dired-do-create-files 'copy (function dired-copy-file)
de97d5e8 1737 "Copy"
ea185644
GM
1738 arg dired-keep-marker-copy
1739 nil dired-copy-how-to-fn)))
dd87891b
RS
1740
1741;;;###autoload
1742(defun dired-do-symlink (&optional arg)
1743 "Make symbolic links to current file or all marked (or next ARG) files.
1744When operating on just the current file, you specify the new name.
1745When operating on multiple or marked files, you specify a directory
1746and new symbolic links are made in that directory
dcaf31d3
EZ
1747with the same names that the files currently have. The default
1748suggested for the target directory depends on the value of
806f34d6
EZ
1749`dired-dwim-target', which see.
1750
1751For relative symlinks, use \\[dired-do-relsymlink]."
dd87891b
RS
1752 (interactive "P")
1753 (dired-do-create-files 'symlink (function make-symbolic-link)
1754 "Symlink" arg dired-keep-marker-symlink))
1755
1756;;;###autoload
1757(defun dired-do-hardlink (&optional arg)
1758 "Add names (hard links) current file or all marked (or next ARG) files.
1759When operating on just the current file, you specify the new name.
1760When operating on multiple or marked files, you specify a directory
1761and new hard links are made in that directory
dcaf31d3
EZ
1762with the same names that the files currently have. The default
1763suggested for the target directory depends on the value of
1764`dired-dwim-target', which see."
dd87891b 1765 (interactive "P")
e5369aad 1766 (dired-do-create-files 'hardlink (function dired-hardlink)
dd87891b
RS
1767 "Hardlink" arg dired-keep-marker-hardlink))
1768
e5369aad
RS
1769(defun dired-hardlink (file newname &optional ok-if-already-exists)
1770 (dired-handle-overwrite newname)
1771 ;; error is caught in -create-files
1772 (add-name-to-file file newname ok-if-already-exists)
1773 ;; Update the link count
1774 (dired-relist-file file))
1775
dd87891b
RS
1776;;;###autoload
1777(defun dired-do-rename (&optional arg)
1778 "Rename current file or all marked (or next ARG) files.
1779When renaming just the current file, you specify the new name.
dcaf31d3 1780When renaming multiple or marked files, you specify a directory.
e5369aad 1781This command also renames any buffers that are visiting the files.
dcaf31d3
EZ
1782The default suggested for the target directory depends on the value
1783of `dired-dwim-target', which see."
dd87891b
RS
1784 (interactive "P")
1785 (dired-do-create-files 'move (function dired-rename-file)
1786 "Move" arg dired-keep-marker-rename "Rename"))
1787;;;###end dired-cp.el
83fadedf 1788\f
dd87891b
RS
1789;;; 5K
1790;;;###begin dired-re.el
06b60517
JB
1791(defvar rename-regexp-query)
1792
dd87891b 1793(defun dired-do-create-files-regexp
731ffbd9 1794 (file-creator operation arg regexp newname &optional whole-name marker-char)
dd87891b
RS
1795 ;; Create a new file for each marked file using regexps.
1796 ;; FILE-CREATOR and OPERATION as in dired-create-files.
1797 ;; ARG as in dired-get-marked-files.
1798 ;; Matches each marked file against REGEXP and constructs the new
1799 ;; filename from NEWNAME (like in function replace-match).
731ffbd9 1800 ;; Optional arg WHOLE-NAME means match/replace the whole file name
dd87891b
RS
1801 ;; instead of only the non-directory part of the file.
1802 ;; Optional arg MARKER-CHAR as in dired-create-files.
1803 (let* ((fn-list (dired-get-marked-files nil arg))
dd87891b
RS
1804 (operation-prompt (concat operation " `%s' to `%s'?"))
1805 (rename-regexp-help-form (format "\
1806Type SPC or `y' to %s one match, DEL or `n' to skip to next,
1807`!' to %s all remaining matches with no more questions."
1808 (downcase operation)
1809 (downcase operation)))
1810 (regexp-name-constructor
1811 ;; Function to construct new filename using REGEXP and NEWNAME:
731ffbd9 1812 (if whole-name ; easy (but rare) case
dd87891b
RS
1813 (function
1814 (lambda (from)
1815 (let ((to (dired-string-replace-match regexp from newname))
1816 ;; must bind help-form directly around call to
1817 ;; dired-query
1818 (help-form rename-regexp-help-form))
1819 (if to
1820 (and (dired-query 'rename-regexp-query
1821 operation-prompt
1822 from
1823 to)
1824 to)
1825 (dired-log "%s: %s did not match regexp %s\n"
1826 operation from regexp)))))
731ffbd9 1827 ;; not whole-name, replace non-directory part only
dd87891b
RS
1828 (function
1829 (lambda (from)
1830 (let* ((new (dired-string-replace-match
1831 regexp (file-name-nondirectory from) newname))
1832 (to (and new ; nil means there was no match
1833 (expand-file-name new
1834 (file-name-directory from))))
1835 (help-form rename-regexp-help-form))
1836 (if to
1837 (and (dired-query 'rename-regexp-query
1838 operation-prompt
1839 (dired-make-relative from)
1840 (dired-make-relative to))
1841 to)
1842 (dired-log "%s: %s did not match regexp %s\n"
1843 operation (file-name-nondirectory from) regexp)))))))
1844 rename-regexp-query)
1845 (dired-create-files
1846 file-creator operation fn-list regexp-name-constructor marker-char)))
1847
1848(defun dired-mark-read-regexp (operation)
1849 ;; Prompt user about performing OPERATION.
731ffbd9
KS
1850 ;; Read and return list of: regexp newname arg whole-name.
1851 (let* ((whole-name
dd87891b
RS
1852 (equal 0 (prefix-numeric-value current-prefix-arg)))
1853 (arg
731ffbd9 1854 (if whole-name nil current-prefix-arg))
dd87891b
RS
1855 (regexp
1856 (dired-read-regexp
731ffbd9 1857 (concat (if whole-name "Abs. " "") operation " from (regexp): ")))
dd87891b
RS
1858 (newname
1859 (read-string
731ffbd9
KS
1860 (concat (if whole-name "Abs. " "") operation " " regexp " to: "))))
1861 (list regexp newname arg whole-name)))
dd87891b
RS
1862
1863;;;###autoload
731ffbd9 1864(defun dired-do-rename-regexp (regexp newname &optional arg whole-name)
2b3e941a
EZ
1865 "Rename selected files whose names match REGEXP to NEWNAME.
1866
1867With non-zero prefix argument ARG, the command operates on the next ARG
1868files. Otherwise, it operates on all the marked files, or the current
1869file if none are marked.
1870
dd87891b
RS
1871As each match is found, the user must type a character saying
1872 what to do with it. For directions, type \\[help-command] at that time.
1873NEWNAME may contain \\=\\<n> or \\& as in `query-replace-regexp'.
1874REGEXP defaults to the last regexp used.
57dabf6b
RS
1875
1876With a zero prefix arg, renaming by regexp affects the absolute file name.
1877Normally, only the non-directory part of the file name is used and changed."
dd87891b
RS
1878 (interactive (dired-mark-read-regexp "Rename"))
1879 (dired-do-create-files-regexp
1880 (function dired-rename-file)
731ffbd9 1881 "Rename" arg regexp newname whole-name dired-keep-marker-rename))
dd87891b
RS
1882
1883;;;###autoload
731ffbd9 1884(defun dired-do-copy-regexp (regexp newname &optional arg whole-name)
2b3e941a 1885 "Copy selected files whose names match REGEXP to NEWNAME.
99c364e4 1886See function `dired-do-rename-regexp' for more info."
dd87891b 1887 (interactive (dired-mark-read-regexp "Copy"))
ba1acd68
RS
1888 (let ((dired-recursive-copies nil)) ; No recursive copies.
1889 (dired-do-create-files-regexp
1890 (function dired-copy-file)
1891 (if dired-copy-preserve-time "Copy [-p]" "Copy")
731ffbd9 1892 arg regexp newname whole-name dired-keep-marker-copy)))
dd87891b
RS
1893
1894;;;###autoload
731ffbd9 1895(defun dired-do-hardlink-regexp (regexp newname &optional arg whole-name)
2b3e941a 1896 "Hardlink selected files whose names match REGEXP to NEWNAME.
99c364e4 1897See function `dired-do-rename-regexp' for more info."
dd87891b
RS
1898 (interactive (dired-mark-read-regexp "HardLink"))
1899 (dired-do-create-files-regexp
1900 (function add-name-to-file)
731ffbd9 1901 "HardLink" arg regexp newname whole-name dired-keep-marker-hardlink))
dd87891b
RS
1902
1903;;;###autoload
731ffbd9 1904(defun dired-do-symlink-regexp (regexp newname &optional arg whole-name)
2b3e941a 1905 "Symlink selected files whose names match REGEXP to NEWNAME.
99c364e4 1906See function `dired-do-rename-regexp' for more info."
dd87891b
RS
1907 (interactive (dired-mark-read-regexp "SymLink"))
1908 (dired-do-create-files-regexp
1909 (function make-symbolic-link)
731ffbd9 1910 "SymLink" arg regexp newname whole-name dired-keep-marker-symlink))
dd87891b 1911
06b60517
JB
1912(defvar rename-non-directory-query)
1913
dd87891b
RS
1914(defun dired-create-files-non-directory
1915 (file-creator basename-constructor operation arg)
1916 ;; Perform FILE-CREATOR on the non-directory part of marked files
1917 ;; using function BASENAME-CONSTRUCTOR, with query for each file.
1918 ;; OPERATION like in dired-create-files, ARG as in dired-get-marked-files.
1919 (let (rename-non-directory-query)
1920 (dired-create-files
1921 file-creator
1922 operation
1923 (dired-get-marked-files nil arg)
1924 (function
1925 (lambda (from)
1926 (let ((to (concat (file-name-directory from)
1927 (funcall basename-constructor
1928 (file-name-nondirectory from)))))
1929 (and (let ((help-form (format "\
1930Type SPC or `y' to %s one file, DEL or `n' to skip to next,
1931`!' to %s all remaining matches with no more questions."
1932 (downcase operation)
1933 (downcase operation))))
1934 (dired-query 'rename-non-directory-query
1935 (concat operation " `%s' to `%s'")
1936 (dired-make-relative from)
1937 (dired-make-relative to)))
1938 to))))
1939 dired-keep-marker-rename)))
1940
1941(defun dired-rename-non-directory (basename-constructor operation arg)
1942 (dired-create-files-non-directory
1943 (function dired-rename-file)
1944 basename-constructor operation arg))
1945
1946;;;###autoload
1947(defun dired-upcase (&optional arg)
1948 "Rename all marked (or next ARG) files to upper case."
1949 (interactive "P")
1950 (dired-rename-non-directory (function upcase) "Rename upcase" arg))
1951
1952;;;###autoload
1953(defun dired-downcase (&optional arg)
1954 "Rename all marked (or next ARG) files to lower case."
1955 (interactive "P")
1956 (dired-rename-non-directory (function downcase) "Rename downcase" arg))
1957
1958;;;###end dired-re.el
83fadedf 1959\f
dd87891b
RS
1960;;; 13K
1961;;;###begin dired-ins.el
1962
1963;;;###autoload
1964(defun dired-maybe-insert-subdir (dirname &optional
1965 switches no-error-if-not-dir-p)
1966 "Insert this subdirectory into the same dired buffer.
1967If it is already present, just move to it (type \\[dired-do-redisplay] to refresh),
1968 else inserts it at its natural place (as `ls -lR' would have done).
1969With a prefix arg, you may edit the ls switches used for this listing.
1970 You can add `R' to the switches to expand the whole tree starting at
1971 this subdirectory.
79d123ad
LT
1972This function takes some pains to conform to `ls -lR' output.
1973
1974Dired remembers switches specified with a prefix arg, so that reverting
1975the buffer will not reset them. However, using `dired-undo' to re-insert
1976or delete subdirectories can bypass this machinery. Hence, you sometimes
1977may have to reset some subdirectory switches after a `dired-undo'.
1978You can reset all subdirectory switches to the default using
fad9e9b4 1979\\<dired-mode-map>\\[dired-reset-subdir-switches].
098c61f2 1980See Info node `(emacs)Subdir switches' for more details."
dd87891b
RS
1981 (interactive
1982 (list (dired-get-filename)
1983 (if current-prefix-arg
f2260f48
LT
1984 (read-string "Switches for listing: "
1985 (or dired-subdir-switches dired-actual-switches)))))
dd87891b
RS
1986 (let ((opoint (point)))
1987 ;; We don't need a marker for opoint as the subdir is always
1988 ;; inserted *after* opoint.
1989 (setq dirname (file-name-as-directory dirname))
1990 (or (and (not switches)
1991 (dired-goto-subdir dirname))
1992 (dired-insert-subdir dirname switches no-error-if-not-dir-p))
1993 ;; Push mark so that it's easy to find back. Do this after the
1994 ;; insert message so that the user sees the `Mark set' message.
1995 (push-mark opoint)))
1996
72af9867 1997;;;###autoload
dd87891b
RS
1998(defun dired-insert-subdir (dirname &optional switches no-error-if-not-dir-p)
1999 "Insert this subdirectory into the same dired buffer.
2000If it is already present, overwrites previous entry,
2001 else inserts it at its natural place (as `ls -lR' would have done).
2002With a prefix arg, you may edit the `ls' switches used for this listing.
2003 You can add `R' to the switches to expand the whole tree starting at
2004 this subdirectory.
2005This function takes some pains to conform to `ls -lR' output."
2006 ;; NO-ERROR-IF-NOT-DIR-P needed for special filesystems like
2007 ;; Prospero where dired-ls does the right thing, but
2008 ;; file-directory-p has not been redefined.
2009 (interactive
2010 (list (dired-get-filename)
2011 (if current-prefix-arg
f2260f48
LT
2012 (read-string "Switches for listing: "
2013 (or dired-subdir-switches dired-actual-switches)))))
dd87891b 2014 (setq dirname (file-name-as-directory (expand-file-name dirname)))
dd87891b
RS
2015 (or no-error-if-not-dir-p
2016 (file-directory-p dirname)
2017 (error "Attempt to insert a non-directory: %s" dirname))
2018 (let ((elt (assoc dirname dired-subdir-alist))
f2260f48
LT
2019 (cons (assoc-string dirname dired-switches-alist))
2020 (modflag (buffer-modified-p))
2021 (old-switches switches)
2022 switches-have-R mark-alist case-fold-search buffer-read-only)
2023 (and (not switches) cons (setq switches (cdr cons)))
2024 (dired-insert-subdir-validate dirname switches)
dd87891b
RS
2025 ;; case-fold-search is nil now, so we can test for capital `R':
2026 (if (setq switches-have-R (and switches (string-match "R" switches)))
2027 ;; avoid duplicated subdirs
2028 (setq mark-alist (dired-kill-tree dirname t)))
2029 (if elt
2030 ;; If subdir is already present, remove it and remember its marks
2031 (setq mark-alist (nconc (dired-insert-subdir-del elt) mark-alist))
2032 (dired-insert-subdir-newpos dirname)) ; else compute new position
2033 (dired-insert-subdir-doupdate
2034 dirname elt (dired-insert-subdir-doinsert dirname switches))
f2260f48
LT
2035 (when old-switches
2036 (if cons
2037 (setcdr cons switches)
2038 (push (cons dirname switches) dired-switches-alist)))
2039 (when switches-have-R
2040 (dired-build-subdir-alist switches)
081e4397 2041 (setq switches (dired-replace-in-string "R" "" switches))
f2260f48
LT
2042 (dolist (cur-ass dired-subdir-alist)
2043 (let ((cur-dir (car cur-ass)))
2044 (and (dired-in-this-tree cur-dir dirname)
f2260f48
LT
2045 (let ((cur-cons (assoc-string cur-dir dired-switches-alist)))
2046 (if cur-cons
2047 (setcdr cur-cons switches)
2048 (push (cons cur-dir switches) dired-switches-alist)))))))
dd87891b 2049 (dired-initial-position dirname)
f2260f48
LT
2050 (save-excursion (dired-mark-remembered mark-alist))
2051 (restore-buffer-modified-p modflag)))
dd87891b 2052
dd87891b
RS
2053(defun dired-insert-subdir-validate (dirname &optional switches)
2054 ;; Check that it is valid to insert DIRNAME with SWITCHES.
2055 ;; Signal an error if invalid (e.g. user typed `i' on `..').
d443f37c 2056 (or (dired-in-this-tree dirname (expand-file-name default-directory))
dd87891b 2057 (error "%s: not in this directory tree" dirname))
f2260f48
LT
2058 (let ((real-switches (or switches dired-subdir-switches)))
2059 (when real-switches
dd87891b
RS
2060 (let (case-fold-search)
2061 (mapcar
2062 (function
2063 (lambda (x)
f2260f48 2064 (or (eq (null (string-match x real-switches))
dd87891b 2065 (null (string-match x dired-actual-switches)))
f2260f48
LT
2066 (error
2067 "Can't have dirs with and without -%s switches together" x))))
dd87891b 2068 ;; all switches that make a difference to dired-get-filename:
f2260f48 2069 '("F" "b"))))))
dd87891b
RS
2070
2071(defun dired-alist-add (dir new-marker)
2072 ;; Add new DIR at NEW-MARKER. Sort alist.
2073 (dired-alist-add-1 dir new-marker)
2074 (dired-alist-sort))
2075
2076(defun dired-alist-sort ()
2077 ;; Keep the alist sorted on buffer position.
2078 (setq dired-subdir-alist
2079 (sort dired-subdir-alist
2080 (function (lambda (elt1 elt2)
2081 (> (dired-get-subdir-min elt1)
2082 (dired-get-subdir-min elt2)))))))
2083
0a07c3a9 2084(defun dired-kill-tree (dirname &optional remember-marks kill-root)
616e14f4 2085 "Kill all proper subdirs of DIRNAME, excluding DIRNAME itself.
0a07c3a9
LT
2086Interactively, you can kill DIRNAME as well by using a prefix argument.
2087In interactive use, the command prompts for DIRNAME.
2088
2089When called from Lisp, if REMEMBER-MARKS is non-nil, return an alist
2090of marked files. If KILL-ROOT is non-nil, kill DIRNAME as well."
2091 (interactive "DKill tree below directory: \ni\nP")
2092 (setq dirname (file-name-as-directory (expand-file-name dirname)))
dd87891b
RS
2093 (let ((s-alist dired-subdir-alist) dir m-alist)
2094 (while s-alist
2095 (setq dir (car (car s-alist))
2096 s-alist (cdr s-alist))
0a07c3a9
LT
2097 (and (or kill-root (not (string-equal dir dirname)))
2098 (dired-in-this-tree dir dirname)
2099 (dired-goto-subdir dir)
2100 (setq m-alist (nconc (dired-kill-subdir remember-marks) m-alist))))
dd87891b
RS
2101 m-alist))
2102
2103(defun dired-insert-subdir-newpos (new-dir)
2104 ;; Find pos for new subdir, according to tree order.
2105 ;;(goto-char (point-max))
2106 (let ((alist dired-subdir-alist) elt dir pos new-pos)
2107 (while alist
2108 (setq elt (car alist)
2109 alist (cdr alist)
06b60517 2110 dir (car elt))
dd87891b
RS
2111 (if (dired-tree-lessp dir new-dir)
2112 ;; Insert NEW-DIR after DIR
2113 (setq new-pos (dired-get-subdir-max elt)
2114 alist nil)))
2115 (goto-char new-pos))
2116 ;; want a separating newline between subdirs
2117 (or (eobp)
2118 (forward-line -1))
2119 (insert "\n")
2120 (point))
2121
2122(defun dired-insert-subdir-del (element)
2123 ;; Erase an already present subdir (given by ELEMENT) from buffer.
2124 ;; Move to that buffer position. Return a mark-alist.
2125 (let ((begin-marker (dired-get-subdir-min element)))
2126 (goto-char begin-marker)
2127 ;; Are at beginning of subdir (and inside it!). Now determine its end:
2128 (goto-char (dired-subdir-max))
2129 (or (eobp);; want a separating newline _between_ subdirs:
2130 (forward-char -1))
2131 (prog1
2132 (dired-remember-marks begin-marker (point))
2133 (delete-region begin-marker (point)))))
2134
2135(defun dired-insert-subdir-doinsert (dirname switches)
e5369aad 2136 ;; Insert ls output after point.
dd87891b 2137 ;; Return the boundary of the inserted text (as list of BEG and END).
349254d3
AS
2138 (save-excursion
2139 (let ((begin (point)))
349254d3
AS
2140 (let ((dired-actual-switches
2141 (or switches
f2260f48 2142 dired-subdir-switches
349254d3
AS
2143 (dired-replace-in-string "R" "" dired-actual-switches))))
2144 (if (equal dirname (car (car (last dired-subdir-alist))))
2145 ;; If doing the top level directory of the buffer,
2146 ;; redo it as specified in dired-directory.
2147 (dired-readin-insert)
2148 (dired-insert-directory dirname dired-actual-switches nil nil t)))
349254d3 2149 (list begin (point)))))
dd87891b
RS
2150
2151(defun dired-insert-subdir-doupdate (dirname elt beg-end)
2152 ;; Point is at the correct subdir alist position for ELT,
2153 ;; BEG-END is the subdir-region (as list of begin and end).
2154 (if elt ; subdir was already present
2155 ;; update its position (should actually be unchanged)
2156 (set-marker (dired-get-subdir-min elt) (point-marker))
2157 (dired-alist-add dirname (point-marker)))
2158 ;; The hook may depend on the subdir-alist containing the just
2159 ;; inserted subdir, so run it after dired-alist-add:
2160 (if dired-after-readin-hook
2161 (save-excursion
2162 (let ((begin (nth 0 beg-end))
2163 (end (nth 1 beg-end)))
2164 (goto-char begin)
2165 (save-restriction
2166 (narrow-to-region begin end)
2167 ;; hook may add or delete lines, but the subdir boundary
2168 ;; marker floats
2169 (run-hooks 'dired-after-readin-hook))))))
2170
2171(defun dired-tree-lessp (dir1 dir2)
57dabf6b 2172 ;; Lexicographic order on file name components, like `ls -lR':
4837b516
GM
2173 ;; DIR1 < DIR2 if DIR1 comes *before* DIR2 in an `ls -lR' listing,
2174 ;; i.e., if DIR1 is a (grand)parent dir of DIR2,
dd87891b
RS
2175 ;; or DIR1 and DIR2 are in the same parentdir and their last
2176 ;; components are string-lessp.
2177 ;; Thus ("/usr/" "/usr/bin") and ("/usr/a/" "/usr/b/") are tree-lessp.
2178 ;; string-lessp could arguably be replaced by file-newer-than-file-p
2179 ;; if dired-actual-switches contained `t'.
2180 (setq dir1 (file-name-as-directory dir1)
2181 dir2 (file-name-as-directory dir2))
2182 (let ((components-1 (dired-split "/" dir1))
2183 (components-2 (dired-split "/" dir2)))
2184 (while (and components-1
2185 components-2
2186 (equal (car components-1) (car components-2)))
2187 (setq components-1 (cdr components-1)
2188 components-2 (cdr components-2)))
2189 (let ((c1 (car components-1))
2190 (c2 (car components-2)))
2191
2192 (cond ((and c1 c2)
2193 (string-lessp c1 c2))
2194 ((and (null c1) (null c2))
2195 nil) ; they are equal, not lessp
2196 ((null c1) ; c2 is a subdir of c1: c1<c2
2197 t)
2198 ((null c2) ; c1 is a subdir of c2: c1>c2
2199 nil)
2200 (t (error "This can't happen"))))))
2201
2202;; There should be a builtin split function - inverse to mapconcat.
2203(defun dired-split (pat str &optional limit)
2204 "Splitting on regexp PAT, turn string STR into a list of substrings.
2205Optional third arg LIMIT (>= 1) is a limit to the length of the
2206resulting list.
2207Thus, if SEP is a regexp that only matches itself,
2208
2209 (mapconcat 'identity (dired-split SEP STRING) SEP)
2210
2211is always equal to STRING."
2212 (let* ((start (string-match pat str))
2213 (result (list (substring str 0 start)))
2214 (count 1)
2215 (end (if start (match-end 0))))
2216 (if end ; else nothing left
2217 (while (and (or (not (integerp limit))
2218 (< count limit))
2219 (string-match pat str end))
2220 (setq start (match-beginning 0)
2221 count (1+ count)
2222 result (cons (substring str end start) result)
2223 end (match-end 0)
2224 start end)
2225 ))
2226 (if (and (or (not (integerp limit))
2227 (< count limit))
2228 end) ; else nothing left
2229 (setq result
2230 (cons (substring str end) result)))
2231 (nreverse result)))
83fadedf 2232\f
dd87891b
RS
2233;;; moving by subdirectories
2234
dd87891b
RS
2235;;;###autoload
2236(defun dired-prev-subdir (arg &optional no-error-if-not-found no-skip)
2237 "Go to previous subdirectory, regardless of level.
2238When called interactively and not on a subdir line, go to this subdir's line."
2239 ;;(interactive "p")
2240 (interactive
2241 (list (if current-prefix-arg
2242 (prefix-numeric-value current-prefix-arg)
2243 ;; if on subdir start already, don't stay there!
2244 (if (dired-get-subdir) 1 0))))
2245 (dired-next-subdir (- arg) no-error-if-not-found no-skip))
2246
2247(defun dired-subdir-min ()
2248 (save-excursion
2249 (if (not (dired-prev-subdir 0 t t))
2250 (error "Not in a subdir!")
2251 (point))))
2252
2253;;;###autoload
2254(defun dired-goto-subdir (dir)
2255 "Go to end of header line of DIR in this dired buffer.
2256Return value of point on success, otherwise return nil.
2257The next char is either \\n, or \\r if DIR is hidden."
2258 (interactive
2259 (prog1 ; let push-mark display its message
2260 (list (expand-file-name
2261 (completing-read "Goto in situ directory: " ; prompt
2262 dired-subdir-alist ; table
2263 nil ; predicate
2264 t ; require-match
2265 (dired-current-directory))))
2266 (push-mark)))
2267 (setq dir (file-name-as-directory dir))
2268 (let ((elt (assoc dir dired-subdir-alist)))
2269 (and elt
2270 (goto-char (dired-get-subdir-min elt))
2271 ;; dired-subdir-hidden-p and dired-add-entry depend on point being
2272 ;; at either \r or \n after this function succeeds.
2273 (progn (skip-chars-forward "^\r\n")
2274 (point)))))
83fadedf 2275\f
dd87891b
RS
2276;;;###autoload
2277(defun dired-mark-subdir-files ()
472974e9
RS
2278 "Mark all files except `.' and `..' in current subdirectory.
2279If the Dired buffer shows multiple directories, this command
2280marks the files listed in the subdirectory that point is in."
96149b57 2281 (interactive)
dd87891b
RS
2282 (let ((p-min (dired-subdir-min)))
2283 (dired-mark-files-in-region p-min (dired-subdir-max))))
2284
2285;;;###autoload
2286(defun dired-kill-subdir (&optional remember-marks)
2287 "Remove all lines of current subdirectory.
2288Lower levels are unaffected."
2289 ;; With optional REMEMBER-MARKS, return a mark-alist.
2290 (interactive)
f2260f48
LT
2291 (let* ((beg (dired-subdir-min))
2292 (end (dired-subdir-max))
2293 (modflag (buffer-modified-p))
2294 (cur-dir (dired-current-directory))
2295 (cons (assoc-string cur-dir dired-switches-alist))
2296 buffer-read-only)
dd87891b
RS
2297 (if (equal cur-dir default-directory)
2298 (error "Attempt to kill top level directory"))
2299 (prog1
2300 (if remember-marks (dired-remember-marks beg end))
2301 (delete-region beg end)
2302 (if (eobp) ; don't leave final blank line
2303 (delete-char -1))
f2260f48
LT
2304 (dired-unsubdir cur-dir)
2305 (when cons
2306 (setq dired-switches-alist (delete cons dired-switches-alist)))
2307 (restore-buffer-modified-p modflag))))
dd87891b
RS
2308
2309(defun dired-unsubdir (dir)
2310 ;; Remove DIR from the alist
2311 (setq dired-subdir-alist
2312 (delq (assoc dir dired-subdir-alist) dired-subdir-alist)))
2313
2314;;;###autoload
2315(defun dired-tree-up (arg)
2316 "Go up ARG levels in the dired tree."
2317 (interactive "p")
2318 (let ((dir (dired-current-directory)))
2319 (while (>= arg 1)
2320 (setq arg (1- arg)
2321 dir (file-name-directory (directory-file-name dir))))
2322 ;;(setq dir (expand-file-name dir))
2323 (or (dired-goto-subdir dir)
55535639 2324 (error "Cannot go up to %s - not in this tree" dir))))
dd87891b
RS
2325
2326;;;###autoload
2327(defun dired-tree-down ()
2328 "Go down in the dired tree."
2329 (interactive)
2330 (let ((dir (dired-current-directory)) ; has slash
2331 pos case-fold-search) ; filenames are case sensitive
2332 (let ((rest (reverse dired-subdir-alist)) elt)
2333 (while rest
2334 (setq elt (car rest)
2335 rest (cdr rest))
2336 (if (dired-in-this-tree (directory-file-name (car elt)) dir)
2337 (setq rest nil
2338 pos (dired-goto-subdir (car elt))))))
2339 (if pos
2340 (goto-char pos)
2341 (error "At the bottom"))))
83fadedf 2342\f
dd87891b
RS
2343;;; hiding
2344
2345(defun dired-unhide-subdir ()
2346 (let (buffer-read-only)
2347 (subst-char-in-region (dired-subdir-min) (dired-subdir-max) ?\r ?\n)))
2348
2349(defun dired-hide-check ()
2350 (or selective-display
2351 (error "selective-display must be t for subdir hiding to work!")))
2352
2353(defun dired-subdir-hidden-p (dir)
2354 (and selective-display
2355 (save-excursion
2356 (dired-goto-subdir dir)
2357 (looking-at "\r"))))
2358
2359;;;###autoload
2360(defun dired-hide-subdir (arg)
2361 "Hide or unhide the current subdirectory and move to next directory.
2362Optional prefix arg is a repeat factor.
2363Use \\[dired-hide-all] to (un)hide all directories."
2364 (interactive "p")
2365 (dired-hide-check)
f2260f48
LT
2366 (let ((modflag (buffer-modified-p)))
2367 (while (>= (setq arg (1- arg)) 0)
2368 (let* ((cur-dir (dired-current-directory))
2369 (hidden-p (dired-subdir-hidden-p cur-dir))
2370 (elt (assoc cur-dir dired-subdir-alist))
2371 (end-pos (1- (dired-get-subdir-max elt)))
2372 buffer-read-only)
2373 ;; keep header line visible, hide rest
2374 (goto-char (dired-get-subdir-min elt))
2375 (skip-chars-forward "^\n\r")
2376 (if hidden-p
2377 (subst-char-in-region (point) end-pos ?\r ?\n)
2378 (subst-char-in-region (point) end-pos ?\n ?\r)))
2379 (dired-next-subdir 1 t))
2380 (restore-buffer-modified-p modflag)))
dd87891b
RS
2381
2382;;;###autoload
8ae41cbc 2383(defun dired-hide-all (&optional ignored)
dd87891b
RS
2384 "Hide all subdirectories, leaving only their header lines.
2385If there is already something hidden, make everything visible again.
2386Use \\[dired-hide-subdir] to (un)hide a particular subdirectory."
2387 (interactive "P")
2388 (dired-hide-check)
f2260f48
LT
2389 (let ((modflag (buffer-modified-p))
2390 buffer-read-only)
dd87891b
RS
2391 (if (save-excursion
2392 (goto-char (point-min))
2393 (search-forward "\r" nil t))
2394 ;; unhide - bombs on \r in filenames
2395 (subst-char-in-region (point-min) (point-max) ?\r ?\n)
2396 ;; hide
2397 (let ((pos (point-max)) ; pos of end of last directory
2398 (alist dired-subdir-alist))
f2260f48 2399 (while alist ; while there are dirs before pos
dd87891b
RS
2400 (subst-char-in-region (dired-get-subdir-min (car alist)) ; pos of prev dir
2401 (save-excursion
2402 (goto-char pos) ; current dir
2403 ;; we're somewhere on current dir's line
2404 (forward-line -1)
2405 (point))
2406 ?\n ?\r)
2407 (setq pos (dired-get-subdir-min (car alist))) ; prev dir gets current dir
f2260f48
LT
2408 (setq alist (cdr alist)))))
2409 (restore-buffer-modified-p modflag)))
dd87891b
RS
2410
2411;;;###end dired-ins.el
2f14b48d 2412
83fadedf 2413\f
b4b6bda2
JL
2414;; Search only in file names in the Dired buffer.
2415
2416(defcustom dired-isearch-filenames nil
9201cc28 2417 "Non-nil to Isearch in file names only.
b9d9c159
JL
2418If t, Isearch in Dired always matches only file names.
2419If `dwim', Isearch matches file names when initial point position is on
2420a file name. Otherwise, it searches the whole buffer without restrictions."
b4b6bda2 2421 :type '(choice (const :tag "No restrictions" nil)
b9d9c159
JL
2422 (const :tag "When point is on a file name initially, search file names" dwim)
2423 (const :tag "Always search in file names" t))
b4b6bda2
JL
2424 :group 'dired
2425 :version "23.1")
2426
43533626 2427(defvar dired-isearch-filter-predicate-orig nil)
b4b6bda2 2428
f1056735
JL
2429(defun dired-isearch-filenames-toggle ()
2430 "Toggle file names searching on or off.
43533626
JL
2431When on, Isearch skips matches outside file names using the predicate
2432`dired-isearch-filter-filenames' that matches only at file names.
04f0aeaf 2433When off, it uses the original predicate."
f1056735 2434 (interactive)
43533626
JL
2435 (setq isearch-filter-predicate
2436 (if (eq isearch-filter-predicate 'dired-isearch-filter-filenames)
04f0aeaf 2437 dired-isearch-filter-predicate-orig
43533626 2438 'dired-isearch-filter-filenames))
f1056735
JL
2439 (setq isearch-success t isearch-adjusted t)
2440 (isearch-update))
2441
27f7e9b5 2442;;;###autoload
b4b6bda2
JL
2443(defun dired-isearch-filenames-setup ()
2444 "Set up isearch to search in Dired file names.
2445Intended to be added to `isearch-mode-hook'."
b9d9c159
JL
2446 (when (or (eq dired-isearch-filenames t)
2447 (and (eq dired-isearch-filenames 'dwim)
2448 (get-text-property (point) 'dired-filename)))
2449 (setq isearch-message-prefix-add "filename ")
f1056735 2450 (define-key isearch-mode-map "\M-sf" 'dired-isearch-filenames-toggle)
43533626
JL
2451 (setq dired-isearch-filter-predicate-orig
2452 (default-value 'isearch-filter-predicate))
2453 (setq-default isearch-filter-predicate 'dired-isearch-filter-filenames)
b4b6bda2
JL
2454 (add-hook 'isearch-mode-end-hook 'dired-isearch-filenames-end nil t)))
2455
2456(defun dired-isearch-filenames-end ()
2457 "Clean up the Dired file name search after terminating isearch."
b9d9c159 2458 (setq isearch-message-prefix-add nil)
f1056735 2459 (define-key isearch-mode-map "\M-sf" nil)
43533626 2460 (setq-default isearch-filter-predicate dired-isearch-filter-predicate-orig)
b4b6bda2
JL
2461 (remove-hook 'isearch-mode-end-hook 'dired-isearch-filenames-end t))
2462
43533626 2463(defun dired-isearch-filter-filenames (beg end)
04f0aeaf
JL
2464 "Test whether the current search hit is a visible file name.
2465Return non-nil if the text from BEG to END is part of a file
2466name (has the text property `dired-filename') and is visible."
2467 (and (isearch-filter-visible beg end)
b4b6bda2
JL
2468 (if dired-isearch-filenames
2469 (text-property-not-all (min beg end) (max beg end)
2470 'dired-filename nil)
2471 t)))
2472
2473;;;###autoload
2474(defun dired-isearch-filenames ()
2475 "Search for a string using Isearch only in file names in the Dired buffer."
2476 (interactive)
b9d9c159 2477 (let ((dired-isearch-filenames t))
b4b6bda2
JL
2478 (isearch-forward)))
2479
2480;;;###autoload
2481(defun dired-isearch-filenames-regexp ()
2482 "Search for a regexp using Isearch only in file names in the Dired buffer."
2483 (interactive)
b9d9c159 2484 (let ((dired-isearch-filenames t))
b4b6bda2
JL
2485 (isearch-forward-regexp)))
2486
2487\f
2297e912
RM
2488;; Functions for searching in tags style among marked files.
2489
160c8be6
JL
2490;;;###autoload
2491(defun dired-do-isearch ()
2492 "Search for a string through all marked files using Isearch."
2493 (interactive)
2494 (multi-isearch-files
2495 (dired-get-marked-files nil nil 'dired-nondirectory-p)))
2496
2497;;;###autoload
2498(defun dired-do-isearch-regexp ()
2499 "Search for a regexp through all marked files using Isearch."
2500 (interactive)
2501 (multi-isearch-files-regexp
2502 (dired-get-marked-files nil nil 'dired-nondirectory-p)))
2503
2297e912 2504;;;###autoload
5c0b696b 2505(defun dired-do-search (regexp)
2297e912
RM
2506 "Search through all marked files for a match for REGEXP.
2507Stops when a match is found.
2508To continue searching for next match, use command \\[tags-loop-continue]."
2509 (interactive "sSearch marked files (regexp): ")
5e514c27 2510 (tags-search regexp '(dired-get-marked-files nil nil 'dired-nondirectory-p)))
2297e912
RM
2511
2512;;;###autoload
be3981a8 2513(defun dired-do-query-replace-regexp (from to &optional delimited)
5c0b696b 2514 "Do `query-replace-regexp' of FROM with TO, on all marked files.
2297e912 2515Third arg DELIMITED (prefix arg) means replace only word-delimited matches.
e5374284 2516If you exit (\\[keyboard-quit], RET or q), you can resume the query replace
2297e912
RM
2517with the command \\[tags-loop-continue]."
2518 (interactive
0751a704
JL
2519 (let ((common
2520 (query-replace-read-args
2521 "Query replace regexp in marked files" t t)))
2522 (list (nth 0 common) (nth 1 common) (nth 2 common))))
d1c553c8
RS
2523 (dolist (file (dired-get-marked-files nil nil 'dired-nondirectory-p))
2524 (let ((buffer (get-file-buffer file)))
2525 (if (and buffer (with-current-buffer buffer
2526 buffer-read-only))
60a8f928 2527 (error "File `%s' is visited read-only" file))))
5e514c27
RS
2528 (tags-query-replace from to delimited
2529 '(dired-get-marked-files nil nil 'dired-nondirectory-p)))
2530
2531(defun dired-nondirectory-p (file)
2532 (not (file-directory-p file)))
83fadedf 2533\f
ee6be958
MB
2534;;;###autoload
2535(defun dired-show-file-type (file &optional deref-symlinks)
2536 "Print the type of FILE, according to the `file' command.
26bde865
LMI
2537If you give a prefix to this command, and FILE is a symbolic
2538link, then the type of the file linked to by FILE is printed
2539instead."
ee6be958 2540 (interactive (list (dired-get-filename t) current-prefix-arg))
b967bd19
MA
2541 (let (process-file-side-effects)
2542 (with-temp-buffer
2543 (if deref-symlinks
2544 (process-file "file" nil t t "-L" "--" file)
2545 (process-file "file" nil t t "--" file))
2546 (when (bolp)
2547 (backward-delete-char 1))
2548 (message "%s" (buffer-string)))))
2297e912 2549
80ec9ac5
RS
2550(provide 'dired-aux)
2551
276f1d00
GM
2552;; Local Variables:
2553;; byte-compile-dynamic: t
2554;; generated-autoload-file: "dired.el"
2555;; End:
2556
e5167999 2557;;; dired-aux.el ends here