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