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