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