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