Add 2011 to FSF/AIST copyright years.
[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,
5df4f04c 4;; 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 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))
86a6e8e0
LL
1020 (dired-map-over-marks (let ((fname (dired-get-filename))
1021 ;; Postphone readin hook till we map
1022 ;; over all marked files (Bug#6810).
1023 (dired-after-readin-hook nil))
dd87891b
RS
1024 (message "Redisplaying... %s" fname)
1025 (dired-update-file-line fname))
1026 arg)
86a6e8e0 1027 (run-hooks 'dired-after-readin-hook)
dd87891b
RS
1028 (dired-move-to-filename)
1029 (message "Redisplaying...done")))
79d123ad
LT
1030
1031(defun dired-reset-subdir-switches ()
1032 "Set `dired-switches-alist' to nil and revert dired buffer."
1033 (interactive)
1034 (setq dired-switches-alist nil)
1035 (revert-buffer))
83fadedf 1036\f
dd87891b
RS
1037(defun dired-update-file-line (file)
1038 ;; Delete the current line, and insert an entry for FILE.
1039 ;; If FILE is nil, then just delete the current line.
1040 ;; Keeps any marks that may be present in column one (doing this
1041 ;; here is faster than with dired-add-entry's optional arg).
1042 ;; Does not update other dired buffers. Use dired-relist-entry for that.
1043 (beginning-of-line)
6482fcac
RS
1044 (let ((char (following-char)) (opoint (point))
1045 (buffer-read-only))
dd87891b
RS
1046 (delete-region (point) (progn (forward-line 1) (point)))
1047 (if file
1048 (progn
24193f35 1049 (dired-add-entry file nil t)
dd87891b
RS
1050 ;; Replace space by old marker without moving point.
1051 ;; Faster than goto+insdel inside a save-excursion?
1052 (subst-char-in-region opoint (1+ opoint) ?\040 char))))
1053 (dired-move-to-filename))
1054
d443f37c 1055;;;###autoload
dd87891b
RS
1056(defun dired-add-file (filename &optional marker-char)
1057 (dired-fun-in-all-buffers
b2a59df0 1058 (file-name-directory filename) (file-name-nondirectory filename)
dd87891b
RS
1059 (function dired-add-entry) filename marker-char))
1060
24193f35 1061(defun dired-add-entry (filename &optional marker-char relative)
dd87891b
RS
1062 ;; Add a new entry for FILENAME, optionally marking it
1063 ;; with MARKER-CHAR (a character, else dired-marker-char is used).
1064 ;; Note that this adds the entry `out of order' if files sorted by
1065 ;; time, etc.
1066 ;; At least this version inserts in the right subdirectory (if present).
1067 ;; And it skips "." or ".." (see `dired-trivial-filenames').
1068 ;; Hidden subdirs are exposed if a file is added there.
1069 (setq filename (directory-file-name filename))
1070 ;; Entry is always for files, even if they happen to also be directories
24193f35 1071 (let* ((opoint (point))
03679a46
GM
1072 (cur-dir (dired-current-directory))
1073 (orig-file-name filename)
1074 (directory (if relative cur-dir (file-name-directory filename)))
1075 reason)
24193f35
RS
1076 (setq filename
1077 (if relative
1078 (file-relative-name filename directory)
1079 (file-name-nondirectory filename))
dd87891b
RS
1080 reason
1081 (catch 'not-found
1082 (if (string= directory cur-dir)
1083 (progn
1084 (skip-chars-forward "^\r\n")
1085 (if (eq (following-char) ?\r)
1086 (dired-unhide-subdir))
1087 ;; We are already where we should be, except when
e5369aad 1088 ;; point is before the subdir line or its total line.
dd87891b
RS
1089 (let ((p (dired-after-subdir-garbage cur-dir)))
1090 (if (< (point) p)
1091 (goto-char p))))
1092 ;; else try to find correct place to insert
1093 (if (dired-goto-subdir directory)
03679a46
GM
1094 (progn ;; unhide if necessary
1095 (if (looking-at "\r") ;; point is at end of subdir line
dd87891b
RS
1096 (dired-unhide-subdir))
1097 ;; found - skip subdir and `total' line
1098 ;; and uninteresting files like . and ..
1099 ;; This better not moves into the next subdir!
1100 (dired-goto-next-nontrivial-file))
1101 ;; not found
1102 (throw 'not-found "Subdir not found")))
225feba2 1103 (let (buffer-read-only opoint)
dd87891b 1104 (beginning-of-line)
225feba2 1105 (setq opoint (point))
e5369aad 1106 ;; Don't expand `.'. Show just the file name within directory.
60e4eb54 1107 (let ((default-directory directory))
e5369aad 1108 (dired-insert-directory directory
7f7f59f5 1109 (concat dired-actual-switches " -d")
e5369aad 1110 (list filename)))
416f1c6f 1111 (goto-char opoint)
e5369aad
RS
1112 ;; Put in desired marker char.
1113 (when marker-char
1114 (let ((dired-marker-char
1115 (if (integerp marker-char) marker-char dired-marker-char)))
ac28c6ca 1116 (dired-mark nil)))
cb79b372
RS
1117 ;; Compensate for a bug in ange-ftp.
1118 ;; It inserts the file's absolute name, rather than
1119 ;; the relative one. That may be hard to fix since it
1120 ;; is probably controlled by something in ftp.
edb8d73e 1121 (goto-char opoint)
0c713b6f 1122 (let ((inserted-name (dired-get-filename 'verbatim)))
cb79b372 1123 (if (file-name-directory inserted-name)
e5369aad 1124 (let (props)
cb79b372 1125 (end-of-line)
e5369aad
RS
1126 (forward-char (- (length inserted-name)))
1127 (setq props (text-properties-at (point)))
1128 (delete-char (length inserted-name))
1129 (let ((pt (point)))
1130 (insert filename)
1131 (set-text-properties pt (point) props))
cb79b372
RS
1132 (forward-char 1))
1133 (forward-line 1)))
dd87891b 1134 (forward-line -1)
03679a46
GM
1135 (if dired-after-readin-hook ;; the subdir-alist is not affected...
1136 (save-excursion ;; ...so we can run it right now:
dd87891b
RS
1137 (save-restriction
1138 (beginning-of-line)
1139 (narrow-to-region (point) (save-excursion
1140 (forward-line 1) (point)))
1141 (run-hooks 'dired-after-readin-hook))))
1142 (dired-move-to-filename))
1143 ;; return nil if all went well
1144 nil))
03679a46 1145 (if reason ; don't move away on failure
dd87891b 1146 (goto-char opoint))
03679a46 1147 (not reason))) ; return t on success, nil else
dd87891b 1148
dd87891b
RS
1149(defun dired-after-subdir-garbage (dir)
1150 ;; Return pos of first file line of DIR, skipping header and total
1151 ;; or wildcard lines.
1152 ;; Important: never moves into the next subdir.
1153 ;; DIR is assumed to be unhidden.
dd87891b
RS
1154 (save-excursion
1155 (or (dired-goto-subdir dir) (error "This cannot happen"))
1156 (forward-line 1)
1157 (while (and (not (eolp)) ; don't cross subdir boundary
1158 (not (dired-move-to-filename)))
1159 (forward-line 1))
1160 (point)))
1161
d443f37c 1162;;;###autoload
dd87891b
RS
1163(defun dired-remove-file (file)
1164 (dired-fun-in-all-buffers
b2a59df0
RS
1165 (file-name-directory file) (file-name-nondirectory file)
1166 (function dired-remove-entry) file))
dd87891b
RS
1167
1168(defun dired-remove-entry (file)
1169 (save-excursion
1170 (and (dired-goto-file file)
1171 (let (buffer-read-only)
1172 (delete-region (progn (beginning-of-line) (point))
1173 (save-excursion (forward-line 1) (point)))))))
1174
d443f37c 1175;;;###autoload
dd87891b 1176(defun dired-relist-file (file)
e5369aad 1177 "Create or update the line for FILE in all Dired buffers it would belong in."
dd87891b 1178 (dired-fun-in-all-buffers (file-name-directory file)
b2a59df0 1179 (file-name-nondirectory file)
dd87891b
RS
1180 (function dired-relist-entry) file))
1181
1182(defun dired-relist-entry (file)
1183 ;; Relist the line for FILE, or just add it if it did not exist.
57dabf6b 1184 ;; FILE must be an absolute file name.
dd87891b
RS
1185 (let (buffer-read-only marker)
1186 ;; If cursor is already on FILE's line delete-region will cause
1187 ;; save-excursion to fail because of floating makers,
1188 ;; moving point to beginning of line. Sigh.
1189 (save-excursion
1190 (and (dired-goto-file file)
1191 (delete-region (progn (beginning-of-line)
1192 (setq marker (following-char))
1193 (point))
1194 (save-excursion (forward-line 1) (point))))
1195 (setq file (directory-file-name file))
1196 (dired-add-entry file (if (eq ?\040 marker) nil marker)))))
83fadedf 1197\f
dd87891b
RS
1198;;; Copy, move/rename, making hard and symbolic links
1199
91a7e829 1200(defcustom dired-backup-overwrite nil
9201cc28 1201 "Non-nil if Dired should ask about making backups before overwriting files.
91a7e829
RS
1202Special value `always' suppresses confirmation."
1203 :type '(choice (const :tag "off" nil)
1204 (const :tag "suppress" always)
a9e9b8fa 1205 (other :tag "ask" t))
91a7e829 1206 :group 'dired)
dd87891b 1207
bf0de14d
CY
1208;; This is a fluid var used in dired-handle-overwrite. It should be
1209;; let-bound whenever dired-copy-file etc are called. See
1210;; dired-create-files for an example.
1211(defvar dired-overwrite-confirmed)
6482fcac 1212
dd87891b 1213(defun dired-handle-overwrite (to)
e5369aad 1214 ;; Save old version of file TO that is to be overwritten.
6482fcac 1215 ;; `dired-overwrite-confirmed' and `overwrite-backup-query' are fluid vars
dd87891b 1216 ;; from dired-create-files.
d63a6ae0 1217 (let (backup)
bbfe2308
CY
1218 (when (and dired-backup-overwrite
1219 dired-overwrite-confirmed
1220 (setq backup (car (find-backup-file-name to)))
1221 (or (eq 'always dired-backup-overwrite)
1222 (dired-query 'overwrite-backup-query
1223 "Make backup for existing file `%s'? "
1224 to)))
1225 (rename-file to backup 0) ; confirm overwrite of old backup
1226 (dired-relist-entry backup))))
dd87891b 1227
d443f37c 1228;;;###autoload
dd87891b
RS
1229(defun dired-copy-file (from to ok-flag)
1230 (dired-handle-overwrite to)
c62a8073
RS
1231 (dired-copy-file-recursive from to ok-flag dired-copy-preserve-time t
1232 dired-recursive-copies))
dd87891b 1233
8e845e23
JB
1234(declare-function make-symbolic-link "fileio.c")
1235
ba1acd68
RS
1236(defun dired-copy-file-recursive (from to ok-flag &optional
1237 preserve-time top recursive)
c62a8073
RS
1238 (let ((attrs (file-attributes from))
1239 dirfailed)
3b68c506
RS
1240 (if (and recursive
1241 (eq t (car attrs))
1242 (or (eq recursive 'always)
ce5a3ac0 1243 (yes-or-no-p (format "Recursive copies of %s? " from))))
3b68c506 1244 ;; This is a directory.
b4583b8c 1245 (copy-directory from to dired-copy-preserve-time)
3b68c506
RS
1246 ;; Not a directory.
1247 (or top (dired-handle-overwrite to))
c62a8073
RS
1248 (condition-case err
1249 (if (stringp (car attrs))
1250 ;; It is a symlink
1251 (make-symbolic-link (car attrs) to ok-flag)
1252 (copy-file from to ok-flag dired-copy-preserve-time))
4a725859 1253 (file-date-error
c62a8073
RS
1254 (push (dired-make-relative from)
1255 dired-create-files-failures)
7a547817 1256 (dired-log "Can't set date on %s:\n%s\n" from err))))))
ba1acd68 1257
d443f37c 1258;;;###autoload
e5369aad
RS
1259(defun dired-rename-file (file newname ok-if-already-exists)
1260 (dired-handle-overwrite newname)
1261 (rename-file file newname ok-if-already-exists) ; error is caught in -create-files
dd87891b 1262 ;; Silently rename the visited file of any buffer visiting this file.
e5369aad
RS
1263 (and (get-file-buffer file)
1264 (with-current-buffer (get-file-buffer file)
1265 (set-visited-file-name newname nil t)))
1266 (dired-remove-file file)
dd87891b 1267 ;; See if it's an inserted subdir, and rename that, too.
e5369aad 1268 (dired-rename-subdir file newname))
dd87891b
RS
1269
1270(defun dired-rename-subdir (from-dir to-dir)
1271 (setq from-dir (file-name-as-directory from-dir)
1272 to-dir (file-name-as-directory to-dir))
b2a59df0 1273 (dired-fun-in-all-buffers from-dir nil
dd87891b
RS
1274 (function dired-rename-subdir-1) from-dir to-dir)
1275 ;; Update visited file name of all affected buffers
9df38cef
RS
1276 (let ((expanded-from-dir (expand-file-name from-dir))
1277 (blist (buffer-list)))
dd87891b 1278 (while blist
7fdbcd83 1279 (with-current-buffer (car blist)
dd87891b 1280 (if (and buffer-file-name
9df38cef 1281 (dired-in-this-tree buffer-file-name expanded-from-dir))
dd87891b 1282 (let ((modflag (buffer-modified-p))
83fadedf 1283 (to-file (dired-replace-in-string
dd87891b
RS
1284 (concat "^" (regexp-quote from-dir))
1285 to-dir
1286 buffer-file-name)))
1287 (set-visited-file-name to-file)
1288 (set-buffer-modified-p modflag))))
1289 (setq blist (cdr blist)))))
1290
1291(defun dired-rename-subdir-1 (dir to)
1292 ;; Rename DIR to TO in headerlines and dired-subdir-alist, if DIR or
1293 ;; one of its subdirectories is expanded in this buffer.
9df38cef
RS
1294 (let ((expanded-dir (expand-file-name dir))
1295 (alist dired-subdir-alist)
dd87891b
RS
1296 (elt nil))
1297 (while alist
1298 (setq elt (car alist)
1299 alist (cdr alist))
9df38cef 1300 (if (dired-in-this-tree (car elt) expanded-dir)
dd87891b
RS
1301 ;; ELT's subdir is affected by the rename
1302 (dired-rename-subdir-2 elt dir to)))
1303 (if (equal dir default-directory)
1304 ;; if top level directory was renamed, lots of things have to be
1305 ;; updated:
1306 (progn
1307 (dired-unadvertise dir) ; we no longer dired DIR...
1308 (setq default-directory to
1309 dired-directory (expand-file-name;; this is correct
1310 ;; with and without wildcards
1311 (file-name-nondirectory dired-directory)
1312 to))
1313 (let ((new-name (file-name-nondirectory
1314 (directory-file-name dired-directory))))
1315 ;; try to rename buffer, but just leave old name if new
1316 ;; name would already exist (don't try appending "<%d>")
1317 (or (get-buffer new-name)
1318 (rename-buffer new-name)))
1319 ;; ... we dired TO now:
1320 (dired-advertise)))))
1321
1322(defun dired-rename-subdir-2 (elt dir to)
f2260f48
LT
1323 ;; Update the headerline and dired-subdir-alist element, as well as
1324 ;; dired-switches-alist element, of directory described by
1325 ;; alist-element ELT to reflect the moving of DIR to TO. Thus, ELT
1326 ;; describes either DIR itself or a subdir of DIR.
dd87891b
RS
1327 (save-excursion
1328 (let ((regexp (regexp-quote (directory-file-name dir)))
1329 (newtext (directory-file-name to))
1330 buffer-read-only)
1331 (goto-char (dired-get-subdir-min elt))
1332 ;; Update subdir headerline in buffer
1333 (if (not (looking-at dired-subdir-regexp))
1334 (error "%s not found where expected - dired-subdir-alist broken?"
1335 dir)
1336 (goto-char (match-beginning 1))
1337 (if (re-search-forward regexp (match-end 1) t)
1338 (replace-match newtext t t)
1339 (error "Expected to find `%s' in headerline of %s" dir (car elt))))
f2260f48
LT
1340 ;; Update buffer-local dired-subdir-alist and dired-switches-alist
1341 (let ((cons (assoc-string (car elt) dired-switches-alist))
1342 (cur-dir (dired-normalize-subdir
1343 (dired-replace-in-string regexp newtext (car elt)))))
1344 (setcar elt cur-dir)
1345 (when cons (setcar cons cur-dir))))))
83fadedf 1346\f
dd87891b
RS
1347;; The basic function for half a dozen variations on cp/mv/ln/ln -s.
1348(defun dired-create-files (file-creator operation fn-list name-constructor
1349 &optional marker-char)
1350
1351;; Create a new file for each from a list of existing files. The user
1352;; is queried, dired buffers are updated, and at the end a success or
1353;; failure message is displayed
1354
1355;; FILE-CREATOR must accept three args: oldfile newfile ok-if-already-exists
1356
1357;; It is called for each file and must create newfile, the entry of
1358;; which will be added. The user will be queried if the file already
1359;; exists. If oldfile is removed by FILE-CREATOR (i.e, it is a
1360;; rename), it is FILE-CREATOR's responsibility to update dired
a7acbbe4 1361;; buffers. FILE-CREATOR must abort by signaling a file-error if it
dd87891b
RS
1362;; could not create newfile. The error is caught and logged.
1363
1364;; OPERATION (a capitalized string, e.g. `Copy') describes the
1365;; operation performed. It is used for error logging.
1366
57dabf6b 1367;; FN-LIST is the list of files to copy (full absolute file names).
dd87891b
RS
1368
1369;; NAME-CONSTRUCTOR returns a newfile for every oldfile, or nil to
1370;; skip. If it skips files for other reasons than a direct user
1371;; query, it is supposed to tell why (using dired-log).
1372
1373;; Optional MARKER-CHAR is a character with which to mark every
1374;; newfile's entry, or t to use the current marker character if the
1375;; oldfile was marked.
1376
c62a8073
RS
1377 (let (dired-create-files-failures failures
1378 skipped (success-count 0) (total (length fn-list)))
dd87891b
RS
1379 (let (to overwrite-query
1380 overwrite-backup-query) ; for dired-handle-overwrite
04509548
SM
1381 (dolist (from fn-list)
1382 (setq to (funcall name-constructor from))
1383 (if (equal to from)
1384 (progn
1385 (setq to nil)
1386 (dired-log "Cannot %s to same file: %s\n"
1387 (downcase operation) from)))
1388 (if (not to)
1389 (setq skipped (cons (dired-make-relative from) skipped))
1390 (let* ((overwrite (file-exists-p to))
1391 (dired-overwrite-confirmed ; for dired-handle-overwrite
1392 (and overwrite
1393 (let ((help-form '(format "\
dd87891b
RS
1394Type SPC or `y' to overwrite file `%s',
1395DEL or `n' to skip to next,
1396ESC or `q' to not overwrite any of the remaining files,
1397`!' to overwrite all remaining files with no more questions." to)))
04509548
SM
1398 (dired-query 'overwrite-query
1399 "Overwrite `%s'?" to))))
1400 ;; must determine if FROM is marked before file-creator
1401 ;; gets a chance to delete it (in case of a move).
1402 (actual-marker-char
1403 (cond ((integerp marker-char) marker-char)
1404 (marker-char (dired-file-marker from)) ; slow
1405 (t nil))))
1406 (condition-case err
1407 (progn
1408 (funcall file-creator from to dired-overwrite-confirmed)
1409 (if overwrite
1410 ;; If we get here, file-creator hasn't been aborted
1411 ;; and the old entry (if any) has to be deleted
1412 ;; before adding the new entry.
1413 (dired-remove-file to))
1414 (setq success-count (1+ success-count))
1415 (message "%s: %d of %d" operation success-count total)
1416 (dired-add-file to actual-marker-char))
1417 (file-error ; FILE-CREATOR aborted
1418 (progn
1419 (push (dired-make-relative from)
1420 failures)
1421 (dired-log "%s `%s' to `%s' failed:\n%s\n"
1422 operation from to err))))))))
dd87891b 1423 (cond
c62a8073
RS
1424 (dired-create-files-failures
1425 (setq failures (nconc failures dired-create-files-failures))
1426 (dired-log-summary
1427 (format "%s failed for %d file%s in %d requests"
1428 operation (length failures)
1429 (dired-plural-s (length failures))
1430 total)
1431 failures))
dd87891b
RS
1432 (failures
1433 (dired-log-summary
1434 (format "%s failed for %d of %d file%s"
c62a8073
RS
1435 operation (length failures)
1436 total (dired-plural-s total))
dd87891b
RS
1437 failures))
1438 (skipped
1439 (dired-log-summary
1440 (format "%s: %d of %d file%s skipped"
1441 operation (length skipped) total
1442 (dired-plural-s total))
1443 skipped))
1444 (t
1445 (message "%s: %s file%s"
1446 operation success-count (dired-plural-s success-count)))))
1447 (dired-move-to-filename))
83fadedf 1448\f
dd87891b 1449(defun dired-do-create-files (op-symbol file-creator operation arg
616e14f4
SM
1450 &optional marker-char op1
1451 how-to)
1452 "Create a new file for each marked file.
1453Prompts user for target, which is a directory in which to create
9c8f194d 1454 the new files. Target may also be a plain file if only one marked
dcaf31d3
EZ
1455 file exists. The way the default for the target directory is
1456 computed depends on the value of `dired-dwim-target-directory'.
616e14f4
SM
1457OP-SYMBOL is the symbol for the operation. Function `dired-mark-pop-up'
1458 will determine whether pop-ups are appropriate for this OP-SYMBOL.
1459FILE-CREATOR and OPERATION as in `dired-create-files'.
1460ARG as in `dired-get-marked-files'.
1461Optional arg MARKER-CHAR as in `dired-create-files'.
1462Optional arg OP1 is an alternate form for OPERATION if there is
1463 only one file.
9c8f194d
CY
1464Optional arg HOW-TO determiness how to treat the target.
1465 If HOW-TO is nil, use `file-directory-p' to determine if the
1466 target is a directory. If so, the marked file(s) are created
1467 inside that directory. Otherwise, the target is a plain file;
1468 an error is raised unless there is exactly one marked file.
1469 If HOW-TO is t, target is always treated as a plain file.
1470 Otherwise, HOW-TO should be a function of one argument, TARGET.
1471 If its return value is nil, TARGET is regarded as a plain file.
1472 If it return value is a list, TARGET is a generalized
1473 directory (e.g. some sort of archive). The first element of
1474 this list must be a function with at least four arguments:
1475 operation - as OPERATION above.
1476 rfn-list - list of the relative names for the marked files.
1477 fn-list - list of the absolute names for the marked files.
1478 target - the name of the target itself.
616e14f4 1479 The rest of into-dir are optional arguments.
9c8f194d 1480 For any other return value, TARGET is treated as a directory."
dd87891b
RS
1481 (or op1 (setq op1 operation))
1482 (let* ((fn-list (dired-get-marked-files nil arg))
ba1acd68
RS
1483 (rfn-list (mapcar (function dired-make-relative) fn-list))
1484 (dired-one-file ; fluid variable inside dired-create-files
1485 (and (consp fn-list) (null (cdr fn-list)) (car fn-list)))
75ab0c79
GM
1486 (target-dir (dired-dwim-target-directory))
1487 (default (and dired-one-file
1488 (expand-file-name (file-name-nondirectory (car fn-list))
1489 target-dir)))
e237085f 1490 (defaults (dired-dwim-target-defaults fn-list target-dir))
ba1acd68 1491 (target (expand-file-name ; fluid variable inside dired-create-files
e237085f
JL
1492 (minibuffer-with-setup-hook
1493 (lambda ()
1494 (set (make-local-variable 'minibuffer-default-add-function) nil)
1495 (setq minibuffer-default defaults))
1496 (dired-mark-read-file-name
1497 (concat (if dired-one-file op1 operation) " %s to: ")
1498 target-dir op-symbol arg rfn-list default))))
325fec3c
EZ
1499 (into-dir (cond ((null how-to)
1500 ;; Allow DOS/Windows users to change the letter
1501 ;; case of a directory. If we don't test these
1502 ;; conditions up front, file-directory-p below
1503 ;; will return t because the filesystem is
1504 ;; case-insensitive, and Emacs will try to move
1505 ;; foo -> foo/foo, which fails.
c60ee5e7 1506 (if (and (memq system-type '(ms-dos windows-nt cygwin))
325fec3c
EZ
1507 (eq op-symbol 'move)
1508 dired-one-file
1509 (string= (downcase
1510 (expand-file-name (car fn-list)))
1511 (downcase
1512 (expand-file-name target)))
1513 (not (string=
1514 (file-name-nondirectory (car fn-list))
1515 (file-name-nondirectory target))))
1516 nil
1517 (file-directory-p target)))
dd87891b
RS
1518 ((eq how-to t) nil)
1519 (t (funcall how-to target)))))
ba1acd68
RS
1520 (if (and (consp into-dir) (functionp (car into-dir)))
1521 (apply (car into-dir) operation rfn-list fn-list target (cdr into-dir))
1522 (if (not (or dired-one-file into-dir))
1523 (error "Marked %s: target must be a directory: %s" operation target))
1524 ;; rename-file bombs when moving directories unless we do this:
1525 (or into-dir (setq target (directory-file-name target)))
1526 (dired-create-files
1527 file-creator operation fn-list
1528 (if into-dir ; target is a directory
1529 ;; This function uses fluid variable target when called
1530 ;; inside dired-create-files:
1531 (function
1532 (lambda (from)
1533 (expand-file-name (file-name-nondirectory from) target)))
1534 (function (lambda (from) target)))
1535 marker-char))))
dd87891b
RS
1536
1537;; Read arguments for a marked-files command that wants a file name,
1538;; perhaps popping up the list of marked files.
1539;; ARG is the prefix arg and indicates whether the files came from
1540;; marks (ARG=nil) or a repeat factor (integerp ARG).
1541;; If the current file was used, the list has but one element and ARG
1542;; does not matter. (It is non-nil, non-integer in that case, namely '(4)).
64666d2d
MB
1543;; DEFAULT is the default value to return if the user just hits RET;
1544;; if it is omitted or nil, then the name of the directory is used.
dd87891b 1545
64666d2d
MB
1546(defun dired-mark-read-file-name (prompt dir op-symbol arg files
1547 &optional default)
dd87891b
RS
1548 (dired-mark-pop-up
1549 nil op-symbol files
1550 (function read-file-name)
64666d2d 1551 (format prompt (dired-mark-prompt arg files)) dir default))
dd87891b
RS
1552
1553(defun dired-dwim-target-directory ()
1554 ;; Try to guess which target directory the user may want.
e237085f
JL
1555 ;; If there is a dired buffer displayed in one of the next windows,
1556 ;; use its current subdir, else use current subdir of this dired buffer.
dd87891b
RS
1557 (let ((this-dir (and (eq major-mode 'dired-mode)
1558 (dired-current-directory))))
1559 ;; non-dired buffer may want to profit from this function, e.g. vm-uudecode
1560 (if dired-dwim-target
e237085f
JL
1561 (let* ((other-win (get-window-with-predicate
1562 (lambda (window)
1563 (with-current-buffer (window-buffer window)
1564 (eq major-mode 'dired-mode)))))
1565 (other-dir (and other-win
1566 (with-current-buffer (window-buffer other-win)
1567 (and (eq major-mode 'dired-mode)
1568 (dired-current-directory))))))
dd87891b
RS
1569 (or other-dir this-dir))
1570 this-dir)))
e237085f
JL
1571
1572(defun dired-dwim-target-defaults (fn-list target-dir)
1573 ;; Return a list of default values for file-reading functions in Dired.
1574 ;; This list may contain directories from Dired buffers in other windows.
1575 ;; `fn-list' is a list of file names used to build a list of defaults.
1576 ;; When nil or more than one element, a list of defaults will
1577 ;; contain only directory names. `target-dir' is a directory name
1578 ;; to exclude from the returned list, for the case when this
1579 ;; directory name is already presented in initial input.
1580 ;; For Dired operations that support `dired-dwim-target',
1581 ;; the argument `target-dir' should have the value returned
1582 ;; from `dired-dwim-target-directory'.
1583 (let ((dired-one-file
1584 (and (consp fn-list) (null (cdr fn-list)) (car fn-list)))
1585 (current-dir (and (eq major-mode 'dired-mode)
1586 (dired-current-directory)))
1587 dired-dirs)
1588 ;; Get a list of directories of visible buffers in dired-mode.
1589 (walk-windows (lambda (w)
1590 (with-current-buffer (window-buffer w)
1591 (and (eq major-mode 'dired-mode)
1592 (push (dired-current-directory) dired-dirs)))))
1593 ;; Force the current dir to be the first in the list.
1594 (setq dired-dirs
1595 (delete-dups (delq nil (cons current-dir (nreverse dired-dirs)))))
1596 ;; Remove the target dir (if specified) or the current dir from
1597 ;; default values, because it should be already in initial input.
1598 (setq dired-dirs (delete (or target-dir current-dir) dired-dirs))
1599 ;; Return a list of default values.
1600 (if dired-one-file
1601 ;; For one file operation, provide a list that contains
1602 ;; other directories, other directories with the appended filename
1603 ;; and the current directory with the appended filename, e.g.
1604 ;; 1. /TARGET-DIR/
1605 ;; 2. /TARGET-DIR/FILENAME
1606 ;; 3. /CURRENT-DIR/FILENAME
1607 (append dired-dirs
1608 (mapcar (lambda (dir)
1609 (expand-file-name
1610 (file-name-nondirectory (car fn-list)) dir))
1611 (reverse dired-dirs))
1612 (list (expand-file-name
1613 (file-name-nondirectory (car fn-list))
1614 (or target-dir current-dir))))
1615 ;; For multi-file operation, return only a list of other directories.
1616 dired-dirs)))
1617
83fadedf 1618\f
dd87891b
RS
1619;;;###autoload
1620(defun dired-create-directory (directory)
1621 "Create a directory called DIRECTORY."
1622 (interactive
1623 (list (read-file-name "Create directory: " (dired-current-directory))))
934b4968
JL
1624 (let* ((expanded (directory-file-name (expand-file-name directory)))
1625 (try expanded) new)
1626 ;; Find the topmost nonexistent parent dir (variable `new')
1627 (while (and try (not (file-exists-p try)) (not (equal new try)))
1628 (setq new try
1629 try (directory-file-name (file-name-directory try))))
1630 (make-directory expanded t)
1631 (when new
1632 (dired-add-file new)
1633 (dired-move-to-filename))))
dd87891b
RS
1634
1635(defun dired-into-dir-with-symlinks (target)
1636 (and (file-directory-p target)
1637 (not (file-symlink-p target))))
1638;; This may not always be what you want, especially if target is your
1639;; home directory and it happens to be a symbolic link, as is often the
1640;; case with NFS and automounters. Or if you want to make symlinks
1641;; into directories that themselves are only symlinks, also quite
1642;; common.
1643
1644;; So we don't use this function as value for HOW-TO in
1645;; dired-do-symlink, which has the minor disadvantage of
1646;; making links *into* a symlinked-dir, when you really wanted to
1647;; *overwrite* that symlink. In that (rare, I guess) case, you'll
1648;; just have to remove that symlink by hand before making your marked
1649;; symlinks.
1650
ba1acd68 1651(defvar dired-copy-how-to-fn nil
5a0c3f56 1652 "Either nil or a function used by `dired-do-copy' to determine target.
ba1acd68
RS
1653See HOW-TO argument for `dired-do-create-files'.")
1654
dd87891b
RS
1655;;;###autoload
1656(defun dired-do-copy (&optional arg)
1657 "Copy all marked (or next ARG) files, or copy the current file.
1658This normally preserves the last-modified date when copying.
1659When operating on just the current file, you specify the new name.
b5458fc2
RS
1660When operating on multiple or marked files, you specify a directory,
1661and new copies of these files are made in that directory
dcaf31d3
EZ
1662with the same names that the files currently have. The default
1663suggested for the target directory depends on the value of
ec9581d5
RS
1664`dired-dwim-target', which see.
1665
1666This command copies symbolic links by creating new ones,
1667like `cp -d'."
dd87891b 1668 (interactive "P")
ea185644 1669 (let ((dired-recursive-copies dired-recursive-copies))
ba1acd68 1670 (dired-do-create-files 'copy (function dired-copy-file)
de97d5e8 1671 "Copy"
ea185644
GM
1672 arg dired-keep-marker-copy
1673 nil dired-copy-how-to-fn)))
dd87891b
RS
1674
1675;;;###autoload
1676(defun dired-do-symlink (&optional arg)
1677 "Make symbolic links to current file or all marked (or next ARG) files.
1678When operating on just the current file, you specify the new name.
1679When operating on multiple or marked files, you specify a directory
1680and new symbolic links are made in that directory
dcaf31d3
EZ
1681with the same names that the files currently have. The default
1682suggested for the target directory depends on the value of
806f34d6
EZ
1683`dired-dwim-target', which see.
1684
1685For relative symlinks, use \\[dired-do-relsymlink]."
dd87891b
RS
1686 (interactive "P")
1687 (dired-do-create-files 'symlink (function make-symbolic-link)
1688 "Symlink" arg dired-keep-marker-symlink))
1689
1690;;;###autoload
1691(defun dired-do-hardlink (&optional arg)
1692 "Add names (hard links) current file or all marked (or next ARG) files.
1693When operating on just the current file, you specify the new name.
1694When operating on multiple or marked files, you specify a directory
1695and new hard links are made in that directory
dcaf31d3
EZ
1696with the same names that the files currently have. The default
1697suggested for the target directory depends on the value of
1698`dired-dwim-target', which see."
dd87891b 1699 (interactive "P")
e5369aad 1700 (dired-do-create-files 'hardlink (function dired-hardlink)
dd87891b
RS
1701 "Hardlink" arg dired-keep-marker-hardlink))
1702
e5369aad
RS
1703(defun dired-hardlink (file newname &optional ok-if-already-exists)
1704 (dired-handle-overwrite newname)
1705 ;; error is caught in -create-files
1706 (add-name-to-file file newname ok-if-already-exists)
1707 ;; Update the link count
1708 (dired-relist-file file))
1709
dd87891b
RS
1710;;;###autoload
1711(defun dired-do-rename (&optional arg)
1712 "Rename current file or all marked (or next ARG) files.
1713When renaming just the current file, you specify the new name.
dcaf31d3 1714When renaming multiple or marked files, you specify a directory.
e5369aad 1715This command also renames any buffers that are visiting the files.
dcaf31d3
EZ
1716The default suggested for the target directory depends on the value
1717of `dired-dwim-target', which see."
dd87891b
RS
1718 (interactive "P")
1719 (dired-do-create-files 'move (function dired-rename-file)
1720 "Move" arg dired-keep-marker-rename "Rename"))
1721;;;###end dired-cp.el
83fadedf 1722\f
dd87891b
RS
1723;;; 5K
1724;;;###begin dired-re.el
1725(defun dired-do-create-files-regexp
731ffbd9 1726 (file-creator operation arg regexp newname &optional whole-name marker-char)
dd87891b
RS
1727 ;; Create a new file for each marked file using regexps.
1728 ;; FILE-CREATOR and OPERATION as in dired-create-files.
1729 ;; ARG as in dired-get-marked-files.
1730 ;; Matches each marked file against REGEXP and constructs the new
1731 ;; filename from NEWNAME (like in function replace-match).
731ffbd9 1732 ;; Optional arg WHOLE-NAME means match/replace the whole file name
dd87891b
RS
1733 ;; instead of only the non-directory part of the file.
1734 ;; Optional arg MARKER-CHAR as in dired-create-files.
1735 (let* ((fn-list (dired-get-marked-files nil arg))
1736 (fn-count (length fn-list))
1737 (operation-prompt (concat operation " `%s' to `%s'?"))
1738 (rename-regexp-help-form (format "\
1739Type SPC or `y' to %s one match, DEL or `n' to skip to next,
1740`!' to %s all remaining matches with no more questions."
1741 (downcase operation)
1742 (downcase operation)))
1743 (regexp-name-constructor
1744 ;; Function to construct new filename using REGEXP and NEWNAME:
731ffbd9 1745 (if whole-name ; easy (but rare) case
dd87891b
RS
1746 (function
1747 (lambda (from)
1748 (let ((to (dired-string-replace-match regexp from newname))
1749 ;; must bind help-form directly around call to
1750 ;; dired-query
1751 (help-form rename-regexp-help-form))
1752 (if to
1753 (and (dired-query 'rename-regexp-query
1754 operation-prompt
1755 from
1756 to)
1757 to)
1758 (dired-log "%s: %s did not match regexp %s\n"
1759 operation from regexp)))))
731ffbd9 1760 ;; not whole-name, replace non-directory part only
dd87891b
RS
1761 (function
1762 (lambda (from)
1763 (let* ((new (dired-string-replace-match
1764 regexp (file-name-nondirectory from) newname))
1765 (to (and new ; nil means there was no match
1766 (expand-file-name new
1767 (file-name-directory from))))
1768 (help-form rename-regexp-help-form))
1769 (if to
1770 (and (dired-query 'rename-regexp-query
1771 operation-prompt
1772 (dired-make-relative from)
1773 (dired-make-relative to))
1774 to)
1775 (dired-log "%s: %s did not match regexp %s\n"
1776 operation (file-name-nondirectory from) regexp)))))))
1777 rename-regexp-query)
1778 (dired-create-files
1779 file-creator operation fn-list regexp-name-constructor marker-char)))
1780
1781(defun dired-mark-read-regexp (operation)
1782 ;; Prompt user about performing OPERATION.
731ffbd9
KS
1783 ;; Read and return list of: regexp newname arg whole-name.
1784 (let* ((whole-name
dd87891b
RS
1785 (equal 0 (prefix-numeric-value current-prefix-arg)))
1786 (arg
731ffbd9 1787 (if whole-name nil current-prefix-arg))
dd87891b
RS
1788 (regexp
1789 (dired-read-regexp
731ffbd9 1790 (concat (if whole-name "Abs. " "") operation " from (regexp): ")))
dd87891b
RS
1791 (newname
1792 (read-string
731ffbd9
KS
1793 (concat (if whole-name "Abs. " "") operation " " regexp " to: "))))
1794 (list regexp newname arg whole-name)))
dd87891b
RS
1795
1796;;;###autoload
731ffbd9 1797(defun dired-do-rename-regexp (regexp newname &optional arg whole-name)
2b3e941a
EZ
1798 "Rename selected files whose names match REGEXP to NEWNAME.
1799
1800With non-zero prefix argument ARG, the command operates on the next ARG
1801files. Otherwise, it operates on all the marked files, or the current
1802file if none are marked.
1803
dd87891b
RS
1804As each match is found, the user must type a character saying
1805 what to do with it. For directions, type \\[help-command] at that time.
1806NEWNAME may contain \\=\\<n> or \\& as in `query-replace-regexp'.
1807REGEXP defaults to the last regexp used.
57dabf6b
RS
1808
1809With a zero prefix arg, renaming by regexp affects the absolute file name.
1810Normally, only the non-directory part of the file name is used and changed."
dd87891b
RS
1811 (interactive (dired-mark-read-regexp "Rename"))
1812 (dired-do-create-files-regexp
1813 (function dired-rename-file)
731ffbd9 1814 "Rename" arg regexp newname whole-name dired-keep-marker-rename))
dd87891b
RS
1815
1816;;;###autoload
731ffbd9 1817(defun dired-do-copy-regexp (regexp newname &optional arg whole-name)
2b3e941a 1818 "Copy selected files whose names match REGEXP to NEWNAME.
99c364e4 1819See function `dired-do-rename-regexp' for more info."
dd87891b 1820 (interactive (dired-mark-read-regexp "Copy"))
ba1acd68
RS
1821 (let ((dired-recursive-copies nil)) ; No recursive copies.
1822 (dired-do-create-files-regexp
1823 (function dired-copy-file)
1824 (if dired-copy-preserve-time "Copy [-p]" "Copy")
731ffbd9 1825 arg regexp newname whole-name dired-keep-marker-copy)))
dd87891b
RS
1826
1827;;;###autoload
731ffbd9 1828(defun dired-do-hardlink-regexp (regexp newname &optional arg whole-name)
2b3e941a 1829 "Hardlink selected files whose names match REGEXP to NEWNAME.
99c364e4 1830See function `dired-do-rename-regexp' for more info."
dd87891b
RS
1831 (interactive (dired-mark-read-regexp "HardLink"))
1832 (dired-do-create-files-regexp
1833 (function add-name-to-file)
731ffbd9 1834 "HardLink" arg regexp newname whole-name dired-keep-marker-hardlink))
dd87891b
RS
1835
1836;;;###autoload
731ffbd9 1837(defun dired-do-symlink-regexp (regexp newname &optional arg whole-name)
2b3e941a 1838 "Symlink selected files whose names match REGEXP to NEWNAME.
99c364e4 1839See function `dired-do-rename-regexp' for more info."
dd87891b
RS
1840 (interactive (dired-mark-read-regexp "SymLink"))
1841 (dired-do-create-files-regexp
1842 (function make-symbolic-link)
731ffbd9 1843 "SymLink" arg regexp newname whole-name dired-keep-marker-symlink))
dd87891b
RS
1844
1845(defun dired-create-files-non-directory
1846 (file-creator basename-constructor operation arg)
1847 ;; Perform FILE-CREATOR on the non-directory part of marked files
1848 ;; using function BASENAME-CONSTRUCTOR, with query for each file.
1849 ;; OPERATION like in dired-create-files, ARG as in dired-get-marked-files.
1850 (let (rename-non-directory-query)
1851 (dired-create-files
1852 file-creator
1853 operation
1854 (dired-get-marked-files nil arg)
1855 (function
1856 (lambda (from)
1857 (let ((to (concat (file-name-directory from)
1858 (funcall basename-constructor
1859 (file-name-nondirectory from)))))
1860 (and (let ((help-form (format "\
1861Type SPC or `y' to %s one file, DEL or `n' to skip to next,
1862`!' to %s all remaining matches with no more questions."
1863 (downcase operation)
1864 (downcase operation))))
1865 (dired-query 'rename-non-directory-query
1866 (concat operation " `%s' to `%s'")
1867 (dired-make-relative from)
1868 (dired-make-relative to)))
1869 to))))
1870 dired-keep-marker-rename)))
1871
1872(defun dired-rename-non-directory (basename-constructor operation arg)
1873 (dired-create-files-non-directory
1874 (function dired-rename-file)
1875 basename-constructor operation arg))
1876
1877;;;###autoload
1878(defun dired-upcase (&optional arg)
1879 "Rename all marked (or next ARG) files to upper case."
1880 (interactive "P")
1881 (dired-rename-non-directory (function upcase) "Rename upcase" arg))
1882
1883;;;###autoload
1884(defun dired-downcase (&optional arg)
1885 "Rename all marked (or next ARG) files to lower case."
1886 (interactive "P")
1887 (dired-rename-non-directory (function downcase) "Rename downcase" arg))
1888
1889;;;###end dired-re.el
83fadedf 1890\f
dd87891b
RS
1891;;; 13K
1892;;;###begin dired-ins.el
1893
1894;;;###autoload
1895(defun dired-maybe-insert-subdir (dirname &optional
1896 switches no-error-if-not-dir-p)
1897 "Insert this subdirectory into the same dired buffer.
1898If it is already present, just move to it (type \\[dired-do-redisplay] to refresh),
1899 else inserts it at its natural place (as `ls -lR' would have done).
1900With a prefix arg, you may edit the ls switches used for this listing.
1901 You can add `R' to the switches to expand the whole tree starting at
1902 this subdirectory.
79d123ad
LT
1903This function takes some pains to conform to `ls -lR' output.
1904
1905Dired remembers switches specified with a prefix arg, so that reverting
1906the buffer will not reset them. However, using `dired-undo' to re-insert
1907or delete subdirectories can bypass this machinery. Hence, you sometimes
1908may have to reset some subdirectory switches after a `dired-undo'.
1909You can reset all subdirectory switches to the default using
fad9e9b4 1910\\<dired-mode-map>\\[dired-reset-subdir-switches].
098c61f2 1911See Info node `(emacs)Subdir switches' for more details."
dd87891b
RS
1912 (interactive
1913 (list (dired-get-filename)
1914 (if current-prefix-arg
f2260f48
LT
1915 (read-string "Switches for listing: "
1916 (or dired-subdir-switches dired-actual-switches)))))
dd87891b
RS
1917 (let ((opoint (point)))
1918 ;; We don't need a marker for opoint as the subdir is always
1919 ;; inserted *after* opoint.
1920 (setq dirname (file-name-as-directory dirname))
1921 (or (and (not switches)
1922 (dired-goto-subdir dirname))
1923 (dired-insert-subdir dirname switches no-error-if-not-dir-p))
1924 ;; Push mark so that it's easy to find back. Do this after the
1925 ;; insert message so that the user sees the `Mark set' message.
1926 (push-mark opoint)))
1927
72af9867 1928;;;###autoload
dd87891b
RS
1929(defun dired-insert-subdir (dirname &optional switches no-error-if-not-dir-p)
1930 "Insert this subdirectory into the same dired buffer.
1931If it is already present, overwrites previous entry,
1932 else inserts it at its natural place (as `ls -lR' would have done).
1933With a prefix arg, you may edit the `ls' switches used for this listing.
1934 You can add `R' to the switches to expand the whole tree starting at
1935 this subdirectory.
1936This function takes some pains to conform to `ls -lR' output."
1937 ;; NO-ERROR-IF-NOT-DIR-P needed for special filesystems like
1938 ;; Prospero where dired-ls does the right thing, but
1939 ;; file-directory-p has not been redefined.
1940 (interactive
1941 (list (dired-get-filename)
1942 (if current-prefix-arg
f2260f48
LT
1943 (read-string "Switches for listing: "
1944 (or dired-subdir-switches dired-actual-switches)))))
dd87891b 1945 (setq dirname (file-name-as-directory (expand-file-name dirname)))
dd87891b
RS
1946 (or no-error-if-not-dir-p
1947 (file-directory-p dirname)
1948 (error "Attempt to insert a non-directory: %s" dirname))
1949 (let ((elt (assoc dirname dired-subdir-alist))
f2260f48
LT
1950 (cons (assoc-string dirname dired-switches-alist))
1951 (modflag (buffer-modified-p))
1952 (old-switches switches)
1953 switches-have-R mark-alist case-fold-search buffer-read-only)
1954 (and (not switches) cons (setq switches (cdr cons)))
1955 (dired-insert-subdir-validate dirname switches)
dd87891b
RS
1956 ;; case-fold-search is nil now, so we can test for capital `R':
1957 (if (setq switches-have-R (and switches (string-match "R" switches)))
1958 ;; avoid duplicated subdirs
1959 (setq mark-alist (dired-kill-tree dirname t)))
1960 (if elt
1961 ;; If subdir is already present, remove it and remember its marks
1962 (setq mark-alist (nconc (dired-insert-subdir-del elt) mark-alist))
1963 (dired-insert-subdir-newpos dirname)) ; else compute new position
1964 (dired-insert-subdir-doupdate
1965 dirname elt (dired-insert-subdir-doinsert dirname switches))
f2260f48
LT
1966 (when old-switches
1967 (if cons
1968 (setcdr cons switches)
1969 (push (cons dirname switches) dired-switches-alist)))
1970 (when switches-have-R
1971 (dired-build-subdir-alist switches)
081e4397 1972 (setq switches (dired-replace-in-string "R" "" switches))
f2260f48
LT
1973 (dolist (cur-ass dired-subdir-alist)
1974 (let ((cur-dir (car cur-ass)))
1975 (and (dired-in-this-tree cur-dir dirname)
f2260f48
LT
1976 (let ((cur-cons (assoc-string cur-dir dired-switches-alist)))
1977 (if cur-cons
1978 (setcdr cur-cons switches)
1979 (push (cons cur-dir switches) dired-switches-alist)))))))
dd87891b 1980 (dired-initial-position dirname)
f2260f48
LT
1981 (save-excursion (dired-mark-remembered mark-alist))
1982 (restore-buffer-modified-p modflag)))
dd87891b 1983
dd87891b
RS
1984(defun dired-insert-subdir-validate (dirname &optional switches)
1985 ;; Check that it is valid to insert DIRNAME with SWITCHES.
1986 ;; Signal an error if invalid (e.g. user typed `i' on `..').
d443f37c 1987 (or (dired-in-this-tree dirname (expand-file-name default-directory))
dd87891b 1988 (error "%s: not in this directory tree" dirname))
f2260f48
LT
1989 (let ((real-switches (or switches dired-subdir-switches)))
1990 (when real-switches
dd87891b
RS
1991 (let (case-fold-search)
1992 (mapcar
1993 (function
1994 (lambda (x)
f2260f48 1995 (or (eq (null (string-match x real-switches))
dd87891b 1996 (null (string-match x dired-actual-switches)))
f2260f48
LT
1997 (error
1998 "Can't have dirs with and without -%s switches together" x))))
dd87891b 1999 ;; all switches that make a difference to dired-get-filename:
f2260f48 2000 '("F" "b"))))))
dd87891b
RS
2001
2002(defun dired-alist-add (dir new-marker)
2003 ;; Add new DIR at NEW-MARKER. Sort alist.
2004 (dired-alist-add-1 dir new-marker)
2005 (dired-alist-sort))
2006
2007(defun dired-alist-sort ()
2008 ;; Keep the alist sorted on buffer position.
2009 (setq dired-subdir-alist
2010 (sort dired-subdir-alist
2011 (function (lambda (elt1 elt2)
2012 (> (dired-get-subdir-min elt1)
2013 (dired-get-subdir-min elt2)))))))
2014
0a07c3a9 2015(defun dired-kill-tree (dirname &optional remember-marks kill-root)
616e14f4 2016 "Kill all proper subdirs of DIRNAME, excluding DIRNAME itself.
0a07c3a9
LT
2017Interactively, you can kill DIRNAME as well by using a prefix argument.
2018In interactive use, the command prompts for DIRNAME.
2019
2020When called from Lisp, if REMEMBER-MARKS is non-nil, return an alist
2021of marked files. If KILL-ROOT is non-nil, kill DIRNAME as well."
2022 (interactive "DKill tree below directory: \ni\nP")
2023 (setq dirname (file-name-as-directory (expand-file-name dirname)))
dd87891b
RS
2024 (let ((s-alist dired-subdir-alist) dir m-alist)
2025 (while s-alist
2026 (setq dir (car (car s-alist))
2027 s-alist (cdr s-alist))
0a07c3a9
LT
2028 (and (or kill-root (not (string-equal dir dirname)))
2029 (dired-in-this-tree dir dirname)
2030 (dired-goto-subdir dir)
2031 (setq m-alist (nconc (dired-kill-subdir remember-marks) m-alist))))
dd87891b
RS
2032 m-alist))
2033
2034(defun dired-insert-subdir-newpos (new-dir)
2035 ;; Find pos for new subdir, according to tree order.
2036 ;;(goto-char (point-max))
2037 (let ((alist dired-subdir-alist) elt dir pos new-pos)
2038 (while alist
2039 (setq elt (car alist)
2040 alist (cdr alist)
2041 dir (car elt)
2042 pos (dired-get-subdir-min elt))
2043 (if (dired-tree-lessp dir new-dir)
2044 ;; Insert NEW-DIR after DIR
2045 (setq new-pos (dired-get-subdir-max elt)
2046 alist nil)))
2047 (goto-char new-pos))
2048 ;; want a separating newline between subdirs
2049 (or (eobp)
2050 (forward-line -1))
2051 (insert "\n")
2052 (point))
2053
2054(defun dired-insert-subdir-del (element)
2055 ;; Erase an already present subdir (given by ELEMENT) from buffer.
2056 ;; Move to that buffer position. Return a mark-alist.
2057 (let ((begin-marker (dired-get-subdir-min element)))
2058 (goto-char begin-marker)
2059 ;; Are at beginning of subdir (and inside it!). Now determine its end:
2060 (goto-char (dired-subdir-max))
2061 (or (eobp);; want a separating newline _between_ subdirs:
2062 (forward-char -1))
2063 (prog1
2064 (dired-remember-marks begin-marker (point))
2065 (delete-region begin-marker (point)))))
2066
2067(defun dired-insert-subdir-doinsert (dirname switches)
e5369aad 2068 ;; Insert ls output after point.
dd87891b 2069 ;; Return the boundary of the inserted text (as list of BEG and END).
349254d3
AS
2070 (save-excursion
2071 (let ((begin (point)))
349254d3
AS
2072 (let ((dired-actual-switches
2073 (or switches
f2260f48 2074 dired-subdir-switches
349254d3
AS
2075 (dired-replace-in-string "R" "" dired-actual-switches))))
2076 (if (equal dirname (car (car (last dired-subdir-alist))))
2077 ;; If doing the top level directory of the buffer,
2078 ;; redo it as specified in dired-directory.
2079 (dired-readin-insert)
2080 (dired-insert-directory dirname dired-actual-switches nil nil t)))
349254d3 2081 (list begin (point)))))
dd87891b
RS
2082
2083(defun dired-insert-subdir-doupdate (dirname elt beg-end)
2084 ;; Point is at the correct subdir alist position for ELT,
2085 ;; BEG-END is the subdir-region (as list of begin and end).
2086 (if elt ; subdir was already present
2087 ;; update its position (should actually be unchanged)
2088 (set-marker (dired-get-subdir-min elt) (point-marker))
2089 (dired-alist-add dirname (point-marker)))
2090 ;; The hook may depend on the subdir-alist containing the just
2091 ;; inserted subdir, so run it after dired-alist-add:
2092 (if dired-after-readin-hook
2093 (save-excursion
2094 (let ((begin (nth 0 beg-end))
2095 (end (nth 1 beg-end)))
2096 (goto-char begin)
2097 (save-restriction
2098 (narrow-to-region begin end)
2099 ;; hook may add or delete lines, but the subdir boundary
2100 ;; marker floats
2101 (run-hooks 'dired-after-readin-hook))))))
2102
2103(defun dired-tree-lessp (dir1 dir2)
57dabf6b 2104 ;; Lexicographic order on file name components, like `ls -lR':
4837b516
GM
2105 ;; DIR1 < DIR2 if DIR1 comes *before* DIR2 in an `ls -lR' listing,
2106 ;; i.e., if DIR1 is a (grand)parent dir of DIR2,
dd87891b
RS
2107 ;; or DIR1 and DIR2 are in the same parentdir and their last
2108 ;; components are string-lessp.
2109 ;; Thus ("/usr/" "/usr/bin") and ("/usr/a/" "/usr/b/") are tree-lessp.
2110 ;; string-lessp could arguably be replaced by file-newer-than-file-p
2111 ;; if dired-actual-switches contained `t'.
2112 (setq dir1 (file-name-as-directory dir1)
2113 dir2 (file-name-as-directory dir2))
2114 (let ((components-1 (dired-split "/" dir1))
2115 (components-2 (dired-split "/" dir2)))
2116 (while (and components-1
2117 components-2
2118 (equal (car components-1) (car components-2)))
2119 (setq components-1 (cdr components-1)
2120 components-2 (cdr components-2)))
2121 (let ((c1 (car components-1))
2122 (c2 (car components-2)))
2123
2124 (cond ((and c1 c2)
2125 (string-lessp c1 c2))
2126 ((and (null c1) (null c2))
2127 nil) ; they are equal, not lessp
2128 ((null c1) ; c2 is a subdir of c1: c1<c2
2129 t)
2130 ((null c2) ; c1 is a subdir of c2: c1>c2
2131 nil)
2132 (t (error "This can't happen"))))))
2133
2134;; There should be a builtin split function - inverse to mapconcat.
2135(defun dired-split (pat str &optional limit)
2136 "Splitting on regexp PAT, turn string STR into a list of substrings.
2137Optional third arg LIMIT (>= 1) is a limit to the length of the
2138resulting list.
2139Thus, if SEP is a regexp that only matches itself,
2140
2141 (mapconcat 'identity (dired-split SEP STRING) SEP)
2142
2143is always equal to STRING."
2144 (let* ((start (string-match pat str))
2145 (result (list (substring str 0 start)))
2146 (count 1)
2147 (end (if start (match-end 0))))
2148 (if end ; else nothing left
2149 (while (and (or (not (integerp limit))
2150 (< count limit))
2151 (string-match pat str end))
2152 (setq start (match-beginning 0)
2153 count (1+ count)
2154 result (cons (substring str end start) result)
2155 end (match-end 0)
2156 start end)
2157 ))
2158 (if (and (or (not (integerp limit))
2159 (< count limit))
2160 end) ; else nothing left
2161 (setq result
2162 (cons (substring str end) result)))
2163 (nreverse result)))
83fadedf 2164\f
dd87891b
RS
2165;;; moving by subdirectories
2166
dd87891b
RS
2167;;;###autoload
2168(defun dired-prev-subdir (arg &optional no-error-if-not-found no-skip)
2169 "Go to previous subdirectory, regardless of level.
2170When called interactively and not on a subdir line, go to this subdir's line."
2171 ;;(interactive "p")
2172 (interactive
2173 (list (if current-prefix-arg
2174 (prefix-numeric-value current-prefix-arg)
2175 ;; if on subdir start already, don't stay there!
2176 (if (dired-get-subdir) 1 0))))
2177 (dired-next-subdir (- arg) no-error-if-not-found no-skip))
2178
2179(defun dired-subdir-min ()
2180 (save-excursion
2181 (if (not (dired-prev-subdir 0 t t))
2182 (error "Not in a subdir!")
2183 (point))))
2184
2185;;;###autoload
2186(defun dired-goto-subdir (dir)
2187 "Go to end of header line of DIR in this dired buffer.
2188Return value of point on success, otherwise return nil.
2189The next char is either \\n, or \\r if DIR is hidden."
2190 (interactive
2191 (prog1 ; let push-mark display its message
2192 (list (expand-file-name
2193 (completing-read "Goto in situ directory: " ; prompt
2194 dired-subdir-alist ; table
2195 nil ; predicate
2196 t ; require-match
2197 (dired-current-directory))))
2198 (push-mark)))
2199 (setq dir (file-name-as-directory dir))
2200 (let ((elt (assoc dir dired-subdir-alist)))
2201 (and elt
2202 (goto-char (dired-get-subdir-min elt))
2203 ;; dired-subdir-hidden-p and dired-add-entry depend on point being
2204 ;; at either \r or \n after this function succeeds.
2205 (progn (skip-chars-forward "^\r\n")
2206 (point)))))
83fadedf 2207\f
dd87891b
RS
2208;;;###autoload
2209(defun dired-mark-subdir-files ()
472974e9
RS
2210 "Mark all files except `.' and `..' in current subdirectory.
2211If the Dired buffer shows multiple directories, this command
2212marks the files listed in the subdirectory that point is in."
96149b57 2213 (interactive)
dd87891b
RS
2214 (let ((p-min (dired-subdir-min)))
2215 (dired-mark-files-in-region p-min (dired-subdir-max))))
2216
2217;;;###autoload
2218(defun dired-kill-subdir (&optional remember-marks)
2219 "Remove all lines of current subdirectory.
2220Lower levels are unaffected."
2221 ;; With optional REMEMBER-MARKS, return a mark-alist.
2222 (interactive)
f2260f48
LT
2223 (let* ((beg (dired-subdir-min))
2224 (end (dired-subdir-max))
2225 (modflag (buffer-modified-p))
2226 (cur-dir (dired-current-directory))
2227 (cons (assoc-string cur-dir dired-switches-alist))
2228 buffer-read-only)
dd87891b
RS
2229 (if (equal cur-dir default-directory)
2230 (error "Attempt to kill top level directory"))
2231 (prog1
2232 (if remember-marks (dired-remember-marks beg end))
2233 (delete-region beg end)
2234 (if (eobp) ; don't leave final blank line
2235 (delete-char -1))
f2260f48
LT
2236 (dired-unsubdir cur-dir)
2237 (when cons
2238 (setq dired-switches-alist (delete cons dired-switches-alist)))
2239 (restore-buffer-modified-p modflag))))
dd87891b
RS
2240
2241(defun dired-unsubdir (dir)
2242 ;; Remove DIR from the alist
2243 (setq dired-subdir-alist
2244 (delq (assoc dir dired-subdir-alist) dired-subdir-alist)))
2245
2246;;;###autoload
2247(defun dired-tree-up (arg)
2248 "Go up ARG levels in the dired tree."
2249 (interactive "p")
2250 (let ((dir (dired-current-directory)))
2251 (while (>= arg 1)
2252 (setq arg (1- arg)
2253 dir (file-name-directory (directory-file-name dir))))
2254 ;;(setq dir (expand-file-name dir))
2255 (or (dired-goto-subdir dir)
55535639 2256 (error "Cannot go up to %s - not in this tree" dir))))
dd87891b
RS
2257
2258;;;###autoload
2259(defun dired-tree-down ()
2260 "Go down in the dired tree."
2261 (interactive)
2262 (let ((dir (dired-current-directory)) ; has slash
2263 pos case-fold-search) ; filenames are case sensitive
2264 (let ((rest (reverse dired-subdir-alist)) elt)
2265 (while rest
2266 (setq elt (car rest)
2267 rest (cdr rest))
2268 (if (dired-in-this-tree (directory-file-name (car elt)) dir)
2269 (setq rest nil
2270 pos (dired-goto-subdir (car elt))))))
2271 (if pos
2272 (goto-char pos)
2273 (error "At the bottom"))))
83fadedf 2274\f
dd87891b
RS
2275;;; hiding
2276
2277(defun dired-unhide-subdir ()
2278 (let (buffer-read-only)
2279 (subst-char-in-region (dired-subdir-min) (dired-subdir-max) ?\r ?\n)))
2280
2281(defun dired-hide-check ()
2282 (or selective-display
2283 (error "selective-display must be t for subdir hiding to work!")))
2284
2285(defun dired-subdir-hidden-p (dir)
2286 (and selective-display
2287 (save-excursion
2288 (dired-goto-subdir dir)
2289 (looking-at "\r"))))
2290
2291;;;###autoload
2292(defun dired-hide-subdir (arg)
2293 "Hide or unhide the current subdirectory and move to next directory.
2294Optional prefix arg is a repeat factor.
2295Use \\[dired-hide-all] to (un)hide all directories."
2296 (interactive "p")
2297 (dired-hide-check)
f2260f48
LT
2298 (let ((modflag (buffer-modified-p)))
2299 (while (>= (setq arg (1- arg)) 0)
2300 (let* ((cur-dir (dired-current-directory))
2301 (hidden-p (dired-subdir-hidden-p cur-dir))
2302 (elt (assoc cur-dir dired-subdir-alist))
2303 (end-pos (1- (dired-get-subdir-max elt)))
2304 buffer-read-only)
2305 ;; keep header line visible, hide rest
2306 (goto-char (dired-get-subdir-min elt))
2307 (skip-chars-forward "^\n\r")
2308 (if hidden-p
2309 (subst-char-in-region (point) end-pos ?\r ?\n)
2310 (subst-char-in-region (point) end-pos ?\n ?\r)))
2311 (dired-next-subdir 1 t))
2312 (restore-buffer-modified-p modflag)))
dd87891b
RS
2313
2314;;;###autoload
8ae41cbc 2315(defun dired-hide-all (&optional ignored)
dd87891b
RS
2316 "Hide all subdirectories, leaving only their header lines.
2317If there is already something hidden, make everything visible again.
2318Use \\[dired-hide-subdir] to (un)hide a particular subdirectory."
2319 (interactive "P")
2320 (dired-hide-check)
f2260f48
LT
2321 (let ((modflag (buffer-modified-p))
2322 buffer-read-only)
dd87891b
RS
2323 (if (save-excursion
2324 (goto-char (point-min))
2325 (search-forward "\r" nil t))
2326 ;; unhide - bombs on \r in filenames
2327 (subst-char-in-region (point-min) (point-max) ?\r ?\n)
2328 ;; hide
2329 (let ((pos (point-max)) ; pos of end of last directory
2330 (alist dired-subdir-alist))
f2260f48 2331 (while alist ; while there are dirs before pos
dd87891b
RS
2332 (subst-char-in-region (dired-get-subdir-min (car alist)) ; pos of prev dir
2333 (save-excursion
2334 (goto-char pos) ; current dir
2335 ;; we're somewhere on current dir's line
2336 (forward-line -1)
2337 (point))
2338 ?\n ?\r)
2339 (setq pos (dired-get-subdir-min (car alist))) ; prev dir gets current dir
f2260f48
LT
2340 (setq alist (cdr alist)))))
2341 (restore-buffer-modified-p modflag)))
dd87891b
RS
2342
2343;;;###end dired-ins.el
2f14b48d 2344
83fadedf 2345\f
b4b6bda2
JL
2346;; Search only in file names in the Dired buffer.
2347
2348(defcustom dired-isearch-filenames nil
9201cc28 2349 "Non-nil to Isearch in file names only.
b9d9c159
JL
2350If t, Isearch in Dired always matches only file names.
2351If `dwim', Isearch matches file names when initial point position is on
2352a file name. Otherwise, it searches the whole buffer without restrictions."
b4b6bda2 2353 :type '(choice (const :tag "No restrictions" nil)
b9d9c159
JL
2354 (const :tag "When point is on a file name initially, search file names" dwim)
2355 (const :tag "Always search in file names" t))
b4b6bda2
JL
2356 :group 'dired
2357 :version "23.1")
2358
43533626 2359(defvar dired-isearch-filter-predicate-orig nil)
b4b6bda2 2360
f1056735
JL
2361(defun dired-isearch-filenames-toggle ()
2362 "Toggle file names searching on or off.
43533626
JL
2363When on, Isearch skips matches outside file names using the predicate
2364`dired-isearch-filter-filenames' that matches only at file names.
04f0aeaf 2365When off, it uses the original predicate."
f1056735 2366 (interactive)
43533626
JL
2367 (setq isearch-filter-predicate
2368 (if (eq isearch-filter-predicate 'dired-isearch-filter-filenames)
04f0aeaf 2369 dired-isearch-filter-predicate-orig
43533626 2370 'dired-isearch-filter-filenames))
f1056735
JL
2371 (setq isearch-success t isearch-adjusted t)
2372 (isearch-update))
2373
27f7e9b5 2374;;;###autoload
b4b6bda2
JL
2375(defun dired-isearch-filenames-setup ()
2376 "Set up isearch to search in Dired file names.
2377Intended to be added to `isearch-mode-hook'."
b9d9c159
JL
2378 (when (or (eq dired-isearch-filenames t)
2379 (and (eq dired-isearch-filenames 'dwim)
2380 (get-text-property (point) 'dired-filename)))
2381 (setq isearch-message-prefix-add "filename ")
f1056735 2382 (define-key isearch-mode-map "\M-sf" 'dired-isearch-filenames-toggle)
43533626
JL
2383 (setq dired-isearch-filter-predicate-orig
2384 (default-value 'isearch-filter-predicate))
2385 (setq-default isearch-filter-predicate 'dired-isearch-filter-filenames)
b4b6bda2
JL
2386 (add-hook 'isearch-mode-end-hook 'dired-isearch-filenames-end nil t)))
2387
2388(defun dired-isearch-filenames-end ()
2389 "Clean up the Dired file name search after terminating isearch."
b9d9c159 2390 (setq isearch-message-prefix-add nil)
f1056735 2391 (define-key isearch-mode-map "\M-sf" nil)
43533626 2392 (setq-default isearch-filter-predicate dired-isearch-filter-predicate-orig)
b4b6bda2
JL
2393 (remove-hook 'isearch-mode-end-hook 'dired-isearch-filenames-end t))
2394
43533626 2395(defun dired-isearch-filter-filenames (beg end)
04f0aeaf
JL
2396 "Test whether the current search hit is a visible file name.
2397Return non-nil if the text from BEG to END is part of a file
2398name (has the text property `dired-filename') and is visible."
2399 (and (isearch-filter-visible beg end)
b4b6bda2
JL
2400 (if dired-isearch-filenames
2401 (text-property-not-all (min beg end) (max beg end)
2402 'dired-filename nil)
2403 t)))
2404
2405;;;###autoload
2406(defun dired-isearch-filenames ()
2407 "Search for a string using Isearch only in file names in the Dired buffer."
2408 (interactive)
b9d9c159 2409 (let ((dired-isearch-filenames t))
b4b6bda2
JL
2410 (isearch-forward)))
2411
2412;;;###autoload
2413(defun dired-isearch-filenames-regexp ()
2414 "Search for a regexp using Isearch only in file names in the Dired buffer."
2415 (interactive)
b9d9c159 2416 (let ((dired-isearch-filenames t))
b4b6bda2
JL
2417 (isearch-forward-regexp)))
2418
2419\f
2297e912
RM
2420;; Functions for searching in tags style among marked files.
2421
160c8be6
JL
2422;;;###autoload
2423(defun dired-do-isearch ()
2424 "Search for a string through all marked files using Isearch."
2425 (interactive)
2426 (multi-isearch-files
2427 (dired-get-marked-files nil nil 'dired-nondirectory-p)))
2428
2429;;;###autoload
2430(defun dired-do-isearch-regexp ()
2431 "Search for a regexp through all marked files using Isearch."
2432 (interactive)
2433 (multi-isearch-files-regexp
2434 (dired-get-marked-files nil nil 'dired-nondirectory-p)))
2435
2297e912 2436;;;###autoload
5c0b696b 2437(defun dired-do-search (regexp)
2297e912
RM
2438 "Search through all marked files for a match for REGEXP.
2439Stops when a match is found.
2440To continue searching for next match, use command \\[tags-loop-continue]."
2441 (interactive "sSearch marked files (regexp): ")
5e514c27 2442 (tags-search regexp '(dired-get-marked-files nil nil 'dired-nondirectory-p)))
2297e912
RM
2443
2444;;;###autoload
be3981a8 2445(defun dired-do-query-replace-regexp (from to &optional delimited)
5c0b696b 2446 "Do `query-replace-regexp' of FROM with TO, on all marked files.
2297e912 2447Third arg DELIMITED (prefix arg) means replace only word-delimited matches.
e5374284 2448If you exit (\\[keyboard-quit], RET or q), you can resume the query replace
2297e912
RM
2449with the command \\[tags-loop-continue]."
2450 (interactive
0751a704
JL
2451 (let ((common
2452 (query-replace-read-args
2453 "Query replace regexp in marked files" t t)))
2454 (list (nth 0 common) (nth 1 common) (nth 2 common))))
d1c553c8
RS
2455 (dolist (file (dired-get-marked-files nil nil 'dired-nondirectory-p))
2456 (let ((buffer (get-file-buffer file)))
2457 (if (and buffer (with-current-buffer buffer
2458 buffer-read-only))
60a8f928 2459 (error "File `%s' is visited read-only" file))))
5e514c27
RS
2460 (tags-query-replace from to delimited
2461 '(dired-get-marked-files nil nil 'dired-nondirectory-p)))
2462
2463(defun dired-nondirectory-p (file)
2464 (not (file-directory-p file)))
83fadedf 2465\f
ee6be958
MB
2466;;;###autoload
2467(defun dired-show-file-type (file &optional deref-symlinks)
2468 "Print the type of FILE, according to the `file' command.
2469If FILE is a symbolic link and the optional argument DEREF-SYMLINKS is
edb8d73e 2470true then the type of the file linked to by FILE is printed instead."
ee6be958 2471 (interactive (list (dired-get-filename t) current-prefix-arg))
b967bd19
MA
2472 (let (process-file-side-effects)
2473 (with-temp-buffer
2474 (if deref-symlinks
2475 (process-file "file" nil t t "-L" "--" file)
2476 (process-file "file" nil t t "--" file))
2477 (when (bolp)
2478 (backward-delete-char 1))
2479 (message "%s" (buffer-string)))))
2297e912 2480
80ec9ac5
RS
2481(provide 'dired-aux)
2482
276f1d00
GM
2483;; Local Variables:
2484;; byte-compile-dynamic: t
2485;; generated-autoload-file: "dired.el"
2486;; End:
2487
cbee283d 2488;; arch-tag: 4b508de9-a153-423d-8d3f-a1bbd86f4f60
e5167999 2489;;; dired-aux.el ends here