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