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