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