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