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