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