(font-lock-extend-jit-lock-region-after-change): Better comment.
[emacs.git] / lisp / dired-aux.el
blob0942c6d1dffc8bb9ee90b4bdd24dc2715e40d5f6
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 (let ((out-name (concat file ".gz")))
749 (and (or (not (file-exists-p out-name))
750 (y-or-n-p
751 (format "File %s already exists. Really compress? "
752 out-name)))
753 (not (dired-check-process (concat "Compressing " file)
754 "gzip" "-f" file))
755 (or (file-exists-p out-name)
756 (setq out-name (concat file ".z")))
757 ;; Rename the compressed file to NEWNAME
758 ;; if it hasn't got that name already.
759 (if (and newname (not (equal newname out-name)))
760 (progn
761 (rename-file out-name newname t)
762 newname)
763 out-name)))
764 (file-error
765 (if (not (dired-check-process (concat "Compressing " file)
766 "compress" "-f" file))
767 ;; Don't use NEWNAME with `compress'.
768 (concat file ".Z"))))))))
770 (defun dired-mark-confirm (op-symbol arg)
771 ;; Request confirmation from the user that the operation described
772 ;; by OP-SYMBOL is to be performed on the marked files.
773 ;; Confirmation consists in a y-or-n question with a file list
774 ;; pop-up unless OP-SYMBOL is a member of `dired-no-confirm'.
775 ;; The files used are determined by ARG (as in dired-get-marked-files).
776 (or (eq dired-no-confirm t)
777 (memq op-symbol dired-no-confirm)
778 ;; Pass t for DISTINGUISH-ONE-MARKED so that a single file which
779 ;; is marked pops up a window. That will help the user see
780 ;; it isn't the current line file.
781 (let ((files (dired-get-marked-files t arg nil t))
782 (string (if (eq op-symbol 'compress) "Compress or uncompress"
783 (capitalize (symbol-name op-symbol)))))
784 (dired-mark-pop-up nil op-symbol files (function y-or-n-p)
785 (concat string " "
786 (dired-mark-prompt arg files) "? ")))))
788 (defun dired-map-over-marks-check (fun arg op-symbol &optional show-progress)
789 ; "Map FUN over marked files (with second ARG like in dired-map-over-marks)
790 ; and display failures.
792 ; FUN takes zero args. It returns non-nil (the offending object, e.g.
793 ; the short form of the filename) for a failure and probably logs a
794 ; detailed error explanation using function `dired-log'.
796 ; OP-SYMBOL is a symbol describing the operation performed (e.g.
797 ; `compress'). It is used with `dired-mark-pop-up' to prompt the user
798 ; (e.g. with `Compress * [2 files]? ') and to display errors (e.g.
799 ; `Failed to compress 1 of 2 files - type W to see why ("foo")')
801 ; SHOW-PROGRESS if non-nil means redisplay dired after each file."
802 (if (dired-mark-confirm op-symbol arg)
803 (let* ((total-list;; all of FUN's return values
804 (dired-map-over-marks (funcall fun) arg show-progress))
805 (total (length total-list))
806 (failures (delq nil total-list))
807 (count (length failures))
808 (string (if (eq op-symbol 'compress) "Compress or uncompress"
809 (capitalize (symbol-name op-symbol)))))
810 (if (not failures)
811 (message "%s: %d file%s."
812 string total (dired-plural-s total))
813 ;; end this bunch of errors:
814 (dired-log-summary
815 (format "Failed to %s %d of %d file%s"
816 (downcase string) count total (dired-plural-s total))
817 failures)))))
819 (defvar dired-query-alist
820 '((?\y . y) (?\040 . y) ; `y' or SPC means accept once
821 (?n . n) (?\177 . n) ; `n' or DEL skips once
822 (?! . yes) ; `!' accepts rest
823 (?q . no) (?\e . no) ; `q' or ESC skips rest
824 ;; None of these keys quit - use C-g for that.
827 ;;;###autoload
828 (defun dired-query (qs-var qs-prompt &rest qs-args)
829 ;; Query user and return nil or t.
830 ;; Store answer in symbol VAR (which must initially be bound to nil).
831 ;; Format PROMPT with ARGS.
832 ;; Binding variable help-form will help the user who types the help key.
833 (let* ((char (symbol-value qs-var))
834 (action (cdr (assoc char dired-query-alist))))
835 (cond ((eq 'yes action)
836 t) ; accept, and don't ask again
837 ((eq 'no action)
838 nil) ; skip, and don't ask again
839 (t;; no lasting effects from last time we asked - ask now
840 (let ((qprompt (concat qs-prompt
841 (if help-form
842 (format " [Type yn!q or %s] "
843 (key-description
844 (char-to-string help-char)))
845 " [Type y, n, q or !] ")))
846 result elt)
847 ;; Actually it looks nicer without cursor-in-echo-area - you can
848 ;; look at the dired buffer instead of at the prompt to decide.
849 (apply 'message qprompt qs-args)
850 (setq char (set qs-var (read-char)))
851 (while (not (setq elt (assoc char dired-query-alist)))
852 (message "Invalid char - type %c for help." help-char)
853 (ding)
854 (sit-for 1)
855 (apply 'message qprompt qs-args)
856 (setq char (set qs-var (read-char))))
857 ;; Display the question with the answer.
858 (message "%s" (concat (apply 'format qprompt qs-args)
859 (char-to-string char)))
860 (memq (cdr elt) '(t y yes)))))))
862 ;;;###autoload
863 (defun dired-do-compress (&optional arg)
864 "Compress or uncompress marked (or next ARG) files."
865 (interactive "P")
866 (dired-map-over-marks-check (function dired-compress) arg 'compress t))
868 ;; Commands for Emacs Lisp files - load and byte compile
870 (defun dired-byte-compile ()
871 ;; Return nil for success, offending file name else.
872 (let* ((filename (dired-get-filename))
873 elc-file buffer-read-only failure)
874 (condition-case err
875 (save-excursion (byte-compile-file filename))
876 (error
877 (setq failure err)))
878 (setq elc-file (byte-compile-dest-file filename))
879 (or (file-exists-p elc-file)
880 (setq failure t))
881 (if failure
882 (progn
883 (dired-log "Byte compile error for %s:\n%s\n" filename failure)
884 (dired-make-relative filename))
885 (dired-remove-file elc-file)
886 (forward-line) ; insert .elc after its .el file
887 (dired-add-file elc-file)
888 nil)))
890 ;;;###autoload
891 (defun dired-do-byte-compile (&optional arg)
892 "Byte compile marked (or next ARG) Emacs Lisp files."
893 (interactive "P")
894 (dired-map-over-marks-check (function dired-byte-compile) arg 'byte-compile t))
896 (defun dired-load ()
897 ;; Return nil for success, offending file name else.
898 (let ((file (dired-get-filename)) failure)
899 (condition-case err
900 (load file nil nil t)
901 (error (setq failure err)))
902 (if (not failure)
904 (dired-log "Load error for %s:\n%s\n" file failure)
905 (dired-make-relative file))))
907 ;;;###autoload
908 (defun dired-do-load (&optional arg)
909 "Load the marked (or next ARG) Emacs Lisp files."
910 (interactive "P")
911 (dired-map-over-marks-check (function dired-load) arg 'load t))
913 ;;;###autoload
914 (defun dired-do-redisplay (&optional arg test-for-subdir)
915 "Redisplay all marked (or next ARG) files.
916 If on a subdir line, redisplay that subdirectory. In that case,
917 a prefix arg lets you edit the `ls' switches used for the new listing.
919 Dired remembers switches specified with a prefix arg, so that reverting
920 the buffer will not reset them. However, using `dired-undo' to re-insert
921 or delete subdirectories can bypass this machinery. Hence, you sometimes
922 may have to reset some subdirectory switches after a `dired-undo'.
923 You can reset all subdirectory switches to the default using
924 \\<dired-mode-map>\\[dired-reset-subdir-switches].
925 See Info node `(emacs)Subdir switches' for more details."
926 ;; Moves point if the next ARG files are redisplayed.
927 (interactive "P\np")
928 (if (and test-for-subdir (dired-get-subdir))
929 (let* ((dir (dired-get-subdir))
930 (switches (cdr (assoc-string dir dired-switches-alist))))
931 (dired-insert-subdir
933 (when arg
934 (read-string "Switches for listing: "
935 (or switches
936 dired-subdir-switches
937 dired-actual-switches)))))
938 (message "Redisplaying...")
939 ;; message much faster than making dired-map-over-marks show progress
940 (dired-uncache
941 (if (consp dired-directory) (car dired-directory) dired-directory))
942 (dired-map-over-marks (let ((fname (dired-get-filename)))
943 (message "Redisplaying... %s" fname)
944 (dired-update-file-line fname))
945 arg)
946 (dired-move-to-filename)
947 (message "Redisplaying...done")))
949 (defun dired-reset-subdir-switches ()
950 "Set `dired-switches-alist' to nil and revert dired buffer."
951 (interactive)
952 (setq dired-switches-alist nil)
953 (revert-buffer))
955 (defun dired-update-file-line (file)
956 ;; Delete the current line, and insert an entry for FILE.
957 ;; If FILE is nil, then just delete the current line.
958 ;; Keeps any marks that may be present in column one (doing this
959 ;; here is faster than with dired-add-entry's optional arg).
960 ;; Does not update other dired buffers. Use dired-relist-entry for that.
961 (beginning-of-line)
962 (let ((char (following-char)) (opoint (point))
963 (buffer-read-only))
964 (delete-region (point) (progn (forward-line 1) (point)))
965 (if file
966 (progn
967 (dired-add-entry file nil t)
968 ;; Replace space by old marker without moving point.
969 ;; Faster than goto+insdel inside a save-excursion?
970 (subst-char-in-region opoint (1+ opoint) ?\040 char))))
971 (dired-move-to-filename))
973 ;;;###autoload
974 (defun dired-add-file (filename &optional marker-char)
975 (dired-fun-in-all-buffers
976 (file-name-directory filename) (file-name-nondirectory filename)
977 (function dired-add-entry) filename marker-char))
979 (defun dired-add-entry (filename &optional marker-char relative)
980 ;; Add a new entry for FILENAME, optionally marking it
981 ;; with MARKER-CHAR (a character, else dired-marker-char is used).
982 ;; Note that this adds the entry `out of order' if files sorted by
983 ;; time, etc.
984 ;; At least this version inserts in the right subdirectory (if present).
985 ;; And it skips "." or ".." (see `dired-trivial-filenames').
986 ;; Hidden subdirs are exposed if a file is added there.
987 (setq filename (directory-file-name filename))
988 ;; Entry is always for files, even if they happen to also be directories
989 (let* ((opoint (point))
990 (cur-dir (dired-current-directory))
991 (orig-file-name filename)
992 (directory (if relative cur-dir (file-name-directory filename)))
993 reason)
994 (setq filename
995 (if relative
996 (file-relative-name filename directory)
997 (file-name-nondirectory filename))
998 reason
999 (catch 'not-found
1000 (if (string= directory cur-dir)
1001 (progn
1002 (skip-chars-forward "^\r\n")
1003 (if (eq (following-char) ?\r)
1004 (dired-unhide-subdir))
1005 ;; We are already where we should be, except when
1006 ;; point is before the subdir line or its total line.
1007 (let ((p (dired-after-subdir-garbage cur-dir)))
1008 (if (< (point) p)
1009 (goto-char p))))
1010 ;; else try to find correct place to insert
1011 (if (dired-goto-subdir directory)
1012 (progn ;; unhide if necessary
1013 (if (looking-at "\r") ;; point is at end of subdir line
1014 (dired-unhide-subdir))
1015 ;; found - skip subdir and `total' line
1016 ;; and uninteresting files like . and ..
1017 ;; This better not moves into the next subdir!
1018 (dired-goto-next-nontrivial-file))
1019 ;; not found
1020 (throw 'not-found "Subdir not found")))
1021 (let (buffer-read-only opoint)
1022 (beginning-of-line)
1023 (setq opoint (point))
1024 ;; Don't expand `.'. Show just the file name within directory.
1025 (let ((default-directory directory))
1026 (dired-insert-directory directory
1027 (concat dired-actual-switches "d")
1028 (list filename)))
1029 (goto-char opoint)
1030 ;; Put in desired marker char.
1031 (when marker-char
1032 (let ((dired-marker-char
1033 (if (integerp marker-char) marker-char dired-marker-char)))
1034 (dired-mark nil)))
1035 ;; Compensate for a bug in ange-ftp.
1036 ;; It inserts the file's absolute name, rather than
1037 ;; the relative one. That may be hard to fix since it
1038 ;; is probably controlled by something in ftp.
1039 (goto-char opoint)
1040 (let ((inserted-name (dired-get-filename 'verbatim)))
1041 (if (file-name-directory inserted-name)
1042 (let (props)
1043 (end-of-line)
1044 (forward-char (- (length inserted-name)))
1045 (setq props (text-properties-at (point)))
1046 (delete-char (length inserted-name))
1047 (let ((pt (point)))
1048 (insert filename)
1049 (set-text-properties pt (point) props))
1050 (forward-char 1))
1051 (forward-line 1)))
1052 (forward-line -1)
1053 (if dired-after-readin-hook ;; the subdir-alist is not affected...
1054 (save-excursion ;; ...so we can run it right now:
1055 (save-restriction
1056 (beginning-of-line)
1057 (narrow-to-region (point) (save-excursion
1058 (forward-line 1) (point)))
1059 (run-hooks 'dired-after-readin-hook))))
1060 (dired-move-to-filename))
1061 ;; return nil if all went well
1062 nil))
1063 (if reason ; don't move away on failure
1064 (goto-char opoint))
1065 (not reason))) ; return t on success, nil else
1067 (defun dired-after-subdir-garbage (dir)
1068 ;; Return pos of first file line of DIR, skipping header and total
1069 ;; or wildcard lines.
1070 ;; Important: never moves into the next subdir.
1071 ;; DIR is assumed to be unhidden.
1072 ;; Will probably be redefined for VMS etc.
1073 (save-excursion
1074 (or (dired-goto-subdir dir) (error "This cannot happen"))
1075 (forward-line 1)
1076 (while (and (not (eolp)) ; don't cross subdir boundary
1077 (not (dired-move-to-filename)))
1078 (forward-line 1))
1079 (point)))
1081 ;;;###autoload
1082 (defun dired-remove-file (file)
1083 (dired-fun-in-all-buffers
1084 (file-name-directory file) (file-name-nondirectory file)
1085 (function dired-remove-entry) file))
1087 (defun dired-remove-entry (file)
1088 (save-excursion
1089 (and (dired-goto-file file)
1090 (let (buffer-read-only)
1091 (delete-region (progn (beginning-of-line) (point))
1092 (save-excursion (forward-line 1) (point)))))))
1094 ;;;###autoload
1095 (defun dired-relist-file (file)
1096 "Create or update the line for FILE in all Dired buffers it would belong in."
1097 (dired-fun-in-all-buffers (file-name-directory file)
1098 (file-name-nondirectory file)
1099 (function dired-relist-entry) file))
1101 (defun dired-relist-entry (file)
1102 ;; Relist the line for FILE, or just add it if it did not exist.
1103 ;; FILE must be an absolute file name.
1104 (let (buffer-read-only marker)
1105 ;; If cursor is already on FILE's line delete-region will cause
1106 ;; save-excursion to fail because of floating makers,
1107 ;; moving point to beginning of line. Sigh.
1108 (save-excursion
1109 (and (dired-goto-file file)
1110 (delete-region (progn (beginning-of-line)
1111 (setq marker (following-char))
1112 (point))
1113 (save-excursion (forward-line 1) (point))))
1114 (setq file (directory-file-name file))
1115 (dired-add-entry file (if (eq ?\040 marker) nil marker)))))
1117 ;;; Copy, move/rename, making hard and symbolic links
1119 (defcustom dired-backup-overwrite nil
1120 "*Non-nil if Dired should ask about making backups before overwriting files.
1121 Special value `always' suppresses confirmation."
1122 :type '(choice (const :tag "off" nil)
1123 (const :tag "suppress" always)
1124 (other :tag "ask" t))
1125 :group 'dired)
1127 (defvar dired-overwrite-confirmed)
1129 (defun dired-handle-overwrite (to)
1130 ;; Save old version of file TO that is to be overwritten.
1131 ;; `dired-overwrite-confirmed' and `overwrite-backup-query' are fluid vars
1132 ;; from dired-create-files.
1133 (let (backup)
1134 (if (and dired-backup-overwrite
1135 dired-overwrite-confirmed
1136 (setq backup (car (find-backup-file-name to)))
1137 (or (eq 'always dired-backup-overwrite)
1138 (dired-query 'overwrite-backup-query
1139 "Make backup for existing file `%s'? "
1140 to)))
1141 (progn
1142 (rename-file to backup 0) ; confirm overwrite of old backup
1143 (dired-relist-entry backup)))))
1145 ;;;###autoload
1146 (defun dired-copy-file (from to ok-flag)
1147 (dired-handle-overwrite to)
1148 (condition-case ()
1149 (dired-copy-file-recursive from to ok-flag dired-copy-preserve-time t
1150 dired-recursive-copies)
1151 (file-date-error (message "Can't set date")
1152 (sit-for 1))))
1154 (defun dired-copy-file-recursive (from to ok-flag &optional
1155 preserve-time top recursive)
1156 (let ((attrs (file-attributes from)))
1157 (if (and recursive
1158 (eq t (car attrs))
1159 (or (eq recursive 'always)
1160 (yes-or-no-p (format "Recursive copies of %s? " from))))
1161 ;; This is a directory.
1162 (let ((files (directory-files from nil dired-re-no-dot)))
1163 (if (eq recursive 'top) (setq recursive 'always)) ; Don't ask any more.
1164 (if (file-exists-p to)
1165 (or top (dired-handle-overwrite to))
1166 (make-directory to))
1167 (while files
1168 (dired-copy-file-recursive
1169 (expand-file-name (car files) from)
1170 (expand-file-name (car files) to)
1171 ok-flag preserve-time nil recursive)
1172 (setq files (cdr files))))
1173 ;; Not a directory.
1174 (or top (dired-handle-overwrite to))
1175 (if (stringp (car attrs))
1176 ;; It is a symlink
1177 (make-symbolic-link (car attrs) to ok-flag)
1178 (copy-file from to ok-flag dired-copy-preserve-time)))))
1180 ;;;###autoload
1181 (defun dired-rename-file (file newname ok-if-already-exists)
1182 (dired-handle-overwrite newname)
1183 (rename-file file newname ok-if-already-exists) ; error is caught in -create-files
1184 ;; Silently rename the visited file of any buffer visiting this file.
1185 (and (get-file-buffer file)
1186 (with-current-buffer (get-file-buffer file)
1187 (set-visited-file-name newname nil t)))
1188 (dired-remove-file file)
1189 ;; See if it's an inserted subdir, and rename that, too.
1190 (dired-rename-subdir file newname))
1192 (defun dired-rename-subdir (from-dir to-dir)
1193 (setq from-dir (file-name-as-directory from-dir)
1194 to-dir (file-name-as-directory to-dir))
1195 (dired-fun-in-all-buffers from-dir nil
1196 (function dired-rename-subdir-1) from-dir to-dir)
1197 ;; Update visited file name of all affected buffers
1198 (let ((expanded-from-dir (expand-file-name from-dir))
1199 (blist (buffer-list)))
1200 (while blist
1201 (save-excursion
1202 (set-buffer (car blist))
1203 (if (and buffer-file-name
1204 (dired-in-this-tree buffer-file-name expanded-from-dir))
1205 (let ((modflag (buffer-modified-p))
1206 (to-file (dired-replace-in-string
1207 (concat "^" (regexp-quote from-dir))
1208 to-dir
1209 buffer-file-name)))
1210 (set-visited-file-name to-file)
1211 (set-buffer-modified-p modflag))))
1212 (setq blist (cdr blist)))))
1214 (defun dired-rename-subdir-1 (dir to)
1215 ;; Rename DIR to TO in headerlines and dired-subdir-alist, if DIR or
1216 ;; one of its subdirectories is expanded in this buffer.
1217 (let ((expanded-dir (expand-file-name dir))
1218 (alist dired-subdir-alist)
1219 (elt nil))
1220 (while alist
1221 (setq elt (car alist)
1222 alist (cdr alist))
1223 (if (dired-in-this-tree (car elt) expanded-dir)
1224 ;; ELT's subdir is affected by the rename
1225 (dired-rename-subdir-2 elt dir to)))
1226 (if (equal dir default-directory)
1227 ;; if top level directory was renamed, lots of things have to be
1228 ;; updated:
1229 (progn
1230 (dired-unadvertise dir) ; we no longer dired DIR...
1231 (setq default-directory to
1232 dired-directory (expand-file-name;; this is correct
1233 ;; with and without wildcards
1234 (file-name-nondirectory dired-directory)
1235 to))
1236 (let ((new-name (file-name-nondirectory
1237 (directory-file-name dired-directory))))
1238 ;; try to rename buffer, but just leave old name if new
1239 ;; name would already exist (don't try appending "<%d>")
1240 (or (get-buffer new-name)
1241 (rename-buffer new-name)))
1242 ;; ... we dired TO now:
1243 (dired-advertise)))))
1245 (defun dired-rename-subdir-2 (elt dir to)
1246 ;; Update the headerline and dired-subdir-alist element, as well as
1247 ;; dired-switches-alist element, of directory described by
1248 ;; alist-element ELT to reflect the moving of DIR to TO. Thus, ELT
1249 ;; describes either DIR itself or a subdir of DIR.
1250 (save-excursion
1251 (let ((regexp (regexp-quote (directory-file-name dir)))
1252 (newtext (directory-file-name to))
1253 buffer-read-only)
1254 (goto-char (dired-get-subdir-min elt))
1255 ;; Update subdir headerline in buffer
1256 (if (not (looking-at dired-subdir-regexp))
1257 (error "%s not found where expected - dired-subdir-alist broken?"
1258 dir)
1259 (goto-char (match-beginning 1))
1260 (if (re-search-forward regexp (match-end 1) t)
1261 (replace-match newtext t t)
1262 (error "Expected to find `%s' in headerline of %s" dir (car elt))))
1263 ;; Update buffer-local dired-subdir-alist and dired-switches-alist
1264 (let ((cons (assoc-string (car elt) dired-switches-alist))
1265 (cur-dir (dired-normalize-subdir
1266 (dired-replace-in-string regexp newtext (car elt)))))
1267 (setcar elt cur-dir)
1268 (when cons (setcar cons cur-dir))))))
1270 ;; The basic function for half a dozen variations on cp/mv/ln/ln -s.
1271 (defun dired-create-files (file-creator operation fn-list name-constructor
1272 &optional marker-char)
1274 ;; Create a new file for each from a list of existing files. The user
1275 ;; is queried, dired buffers are updated, and at the end a success or
1276 ;; failure message is displayed
1278 ;; FILE-CREATOR must accept three args: oldfile newfile ok-if-already-exists
1280 ;; It is called for each file and must create newfile, the entry of
1281 ;; which will be added. The user will be queried if the file already
1282 ;; exists. If oldfile is removed by FILE-CREATOR (i.e, it is a
1283 ;; rename), it is FILE-CREATOR's responsibility to update dired
1284 ;; buffers. FILE-CREATOR must abort by signaling a file-error if it
1285 ;; could not create newfile. The error is caught and logged.
1287 ;; OPERATION (a capitalized string, e.g. `Copy') describes the
1288 ;; operation performed. It is used for error logging.
1290 ;; FN-LIST is the list of files to copy (full absolute file names).
1292 ;; NAME-CONSTRUCTOR returns a newfile for every oldfile, or nil to
1293 ;; skip. If it skips files for other reasons than a direct user
1294 ;; query, it is supposed to tell why (using dired-log).
1296 ;; Optional MARKER-CHAR is a character with which to mark every
1297 ;; newfile's entry, or t to use the current marker character if the
1298 ;; oldfile was marked.
1300 (let (failures skipped (success-count 0) (total (length fn-list)))
1301 (let (to overwrite-query
1302 overwrite-backup-query) ; for dired-handle-overwrite
1303 (mapcar
1304 (function
1305 (lambda (from)
1306 (setq to (funcall name-constructor from))
1307 (if (equal to from)
1308 (progn
1309 (setq to nil)
1310 (dired-log "Cannot %s to same file: %s\n"
1311 (downcase operation) from)))
1312 (if (not to)
1313 (setq skipped (cons (dired-make-relative from) skipped))
1314 (let* ((overwrite (file-exists-p to))
1315 (dired-overwrite-confirmed ; for dired-handle-overwrite
1316 (and overwrite
1317 (let ((help-form '(format "\
1318 Type SPC or `y' to overwrite file `%s',
1319 DEL or `n' to skip to next,
1320 ESC or `q' to not overwrite any of the remaining files,
1321 `!' to overwrite all remaining files with no more questions." to)))
1322 (dired-query 'overwrite-query
1323 "Overwrite `%s'?" to))))
1324 ;; must determine if FROM is marked before file-creator
1325 ;; gets a chance to delete it (in case of a move).
1326 (actual-marker-char
1327 (cond ((integerp marker-char) marker-char)
1328 (marker-char (dired-file-marker from)) ; slow
1329 (t nil))))
1330 (condition-case err
1331 (progn
1332 (funcall file-creator from to dired-overwrite-confirmed)
1333 (if overwrite
1334 ;; If we get here, file-creator hasn't been aborted
1335 ;; and the old entry (if any) has to be deleted
1336 ;; before adding the new entry.
1337 (dired-remove-file to))
1338 (setq success-count (1+ success-count))
1339 (message "%s: %d of %d" operation success-count total)
1340 (dired-add-file to actual-marker-char))
1341 (file-error ; FILE-CREATOR aborted
1342 (progn
1343 (setq failures (cons (dired-make-relative from) failures))
1344 (dired-log "%s `%s' to `%s' failed:\n%s\n"
1345 operation from to err))))))))
1346 fn-list))
1347 (cond
1348 (failures
1349 (dired-log-summary
1350 (format "%s failed for %d of %d file%s"
1351 operation (length failures) total
1352 (dired-plural-s total))
1353 failures))
1354 (skipped
1355 (dired-log-summary
1356 (format "%s: %d of %d file%s skipped"
1357 operation (length skipped) total
1358 (dired-plural-s total))
1359 skipped))
1361 (message "%s: %s file%s"
1362 operation success-count (dired-plural-s success-count)))))
1363 (dired-move-to-filename))
1365 (defun dired-do-create-files (op-symbol file-creator operation arg
1366 &optional marker-char op1
1367 how-to)
1368 "Create a new file for each marked file.
1369 Prompts user for target, which is a directory in which to create
1370 the new files. Target may be a plain file if only one marked
1371 file exists. The way the default for the target directory is
1372 computed depends on the value of `dired-dwim-target-directory'.
1373 OP-SYMBOL is the symbol for the operation. Function `dired-mark-pop-up'
1374 will determine whether pop-ups are appropriate for this OP-SYMBOL.
1375 FILE-CREATOR and OPERATION as in `dired-create-files'.
1376 ARG as in `dired-get-marked-files'.
1377 Optional arg MARKER-CHAR as in `dired-create-files'.
1378 Optional arg OP1 is an alternate form for OPERATION if there is
1379 only one file.
1380 Optional arg HOW-TO is used to set the value of the into-dir variable
1381 which determines how to treat target.
1382 If into-dir is set to nil then target is not regarded as a directory,
1383 there must be exactly one marked file, else error.
1384 Else if into-dir is set to a list, then target is a generalized
1385 directory (e.g. some sort of archive). The first element of into-dir
1386 must be a function with at least four arguments:
1387 operation as OPERATION above.
1388 rfn-list a list of the relative names for the marked files.
1389 fn-list a list of the absolute names for the marked files.
1390 target.
1391 The rest of into-dir are optional arguments.
1392 Else into-dir is not a list. Target is a directory.
1393 The marked file(s) are created inside the target directory.
1395 If HOW-TO is not given (or nil), then into-dir is set to true if
1396 target is a directory and otherwise to nil.
1397 Else if HOW-TO is t, then into-dir is set to nil.
1398 Else HOW-TO is assumed to be a function of one argument, target,
1399 that looks at target and returns a value for the into-dir
1400 variable. The function `dired-into-dir-with-symlinks' is provided
1401 for the case (common when creating symlinks) that symbolic
1402 links to directories are not to be considered as directories
1403 (as `file-directory-p' would if HOW-TO had been nil)."
1404 (or op1 (setq op1 operation))
1405 (let* ((fn-list (dired-get-marked-files nil arg))
1406 (rfn-list (mapcar (function dired-make-relative) fn-list))
1407 (dired-one-file ; fluid variable inside dired-create-files
1408 (and (consp fn-list) (null (cdr fn-list)) (car fn-list)))
1409 (target-dir (dired-dwim-target-directory))
1410 (default (and dired-one-file
1411 (expand-file-name (file-name-nondirectory (car fn-list))
1412 target-dir)))
1413 (target (expand-file-name ; fluid variable inside dired-create-files
1414 (dired-mark-read-file-name
1415 (concat (if dired-one-file op1 operation) " %s to: ")
1416 target-dir op-symbol arg rfn-list default)))
1417 (into-dir (cond ((null how-to)
1418 ;; Allow DOS/Windows users to change the letter
1419 ;; case of a directory. If we don't test these
1420 ;; conditions up front, file-directory-p below
1421 ;; will return t because the filesystem is
1422 ;; case-insensitive, and Emacs will try to move
1423 ;; foo -> foo/foo, which fails.
1424 (if (and (memq system-type '(ms-dos windows-nt cygwin))
1425 (eq op-symbol 'move)
1426 dired-one-file
1427 (string= (downcase
1428 (expand-file-name (car fn-list)))
1429 (downcase
1430 (expand-file-name target)))
1431 (not (string=
1432 (file-name-nondirectory (car fn-list))
1433 (file-name-nondirectory target))))
1435 (file-directory-p target)))
1436 ((eq how-to t) nil)
1437 (t (funcall how-to target)))))
1438 (if (and (consp into-dir) (functionp (car into-dir)))
1439 (apply (car into-dir) operation rfn-list fn-list target (cdr into-dir))
1440 (if (not (or dired-one-file into-dir))
1441 (error "Marked %s: target must be a directory: %s" operation target))
1442 ;; rename-file bombs when moving directories unless we do this:
1443 (or into-dir (setq target (directory-file-name target)))
1444 (dired-create-files
1445 file-creator operation fn-list
1446 (if into-dir ; target is a directory
1447 ;; This function uses fluid variable target when called
1448 ;; inside dired-create-files:
1449 (function
1450 (lambda (from)
1451 (expand-file-name (file-name-nondirectory from) target)))
1452 (function (lambda (from) target)))
1453 marker-char))))
1455 ;; Read arguments for a marked-files command that wants a file name,
1456 ;; perhaps popping up the list of marked files.
1457 ;; ARG is the prefix arg and indicates whether the files came from
1458 ;; marks (ARG=nil) or a repeat factor (integerp ARG).
1459 ;; If the current file was used, the list has but one element and ARG
1460 ;; does not matter. (It is non-nil, non-integer in that case, namely '(4)).
1461 ;; DEFAULT is the default value to return if the user just hits RET;
1462 ;; if it is omitted or nil, then the name of the directory is used.
1464 (defun dired-mark-read-file-name (prompt dir op-symbol arg files
1465 &optional default)
1466 (dired-mark-pop-up
1467 nil op-symbol files
1468 (function read-file-name)
1469 (format prompt (dired-mark-prompt arg files)) dir default))
1471 (defun dired-dwim-target-directory ()
1472 ;; Try to guess which target directory the user may want.
1473 ;; If there is a dired buffer displayed in the next window, use
1474 ;; its current subdir, else use current subdir of this dired buffer.
1475 (let ((this-dir (and (eq major-mode 'dired-mode)
1476 (dired-current-directory))))
1477 ;; non-dired buffer may want to profit from this function, e.g. vm-uudecode
1478 (if dired-dwim-target
1479 (let* ((other-buf (window-buffer (next-window)))
1480 (other-dir (save-excursion
1481 (set-buffer other-buf)
1482 (and (eq major-mode 'dired-mode)
1483 (dired-current-directory)))))
1484 (or other-dir this-dir))
1485 this-dir)))
1487 ;;;###autoload
1488 (defun dired-create-directory (directory)
1489 "Create a directory called DIRECTORY."
1490 (interactive
1491 (list (read-file-name "Create directory: " (dired-current-directory))))
1492 (let ((expanded (directory-file-name (expand-file-name directory))))
1493 (make-directory expanded)
1494 (dired-add-file expanded)
1495 (dired-move-to-filename)))
1497 (defun dired-into-dir-with-symlinks (target)
1498 (and (file-directory-p target)
1499 (not (file-symlink-p target))))
1500 ;; This may not always be what you want, especially if target is your
1501 ;; home directory and it happens to be a symbolic link, as is often the
1502 ;; case with NFS and automounters. Or if you want to make symlinks
1503 ;; into directories that themselves are only symlinks, also quite
1504 ;; common.
1506 ;; So we don't use this function as value for HOW-TO in
1507 ;; dired-do-symlink, which has the minor disadvantage of
1508 ;; making links *into* a symlinked-dir, when you really wanted to
1509 ;; *overwrite* that symlink. In that (rare, I guess) case, you'll
1510 ;; just have to remove that symlink by hand before making your marked
1511 ;; symlinks.
1513 (defvar dired-copy-how-to-fn nil
1514 "nil or a function used by `dired-do-copy' to determine target.
1515 See HOW-TO argument for `dired-do-create-files'.")
1517 ;;;###autoload
1518 (defun dired-do-copy (&optional arg)
1519 "Copy all marked (or next ARG) files, or copy the current file.
1520 This normally preserves the last-modified date when copying.
1521 When operating on just the current file, you specify the new name.
1522 When operating on multiple or marked files, you specify a directory,
1523 and new copies of these files are made in that directory
1524 with the same names that the files currently have. The default
1525 suggested for the target directory depends on the value of
1526 `dired-dwim-target', which see."
1527 (interactive "P")
1528 (let ((dired-recursive-copies dired-recursive-copies))
1529 (dired-do-create-files 'copy (function dired-copy-file)
1530 "Copy"
1531 arg dired-keep-marker-copy
1532 nil dired-copy-how-to-fn)))
1534 ;;;###autoload
1535 (defun dired-do-symlink (&optional arg)
1536 "Make symbolic links to current file or all marked (or next ARG) files.
1537 When operating on just the current file, you specify the new name.
1538 When operating on multiple or marked files, you specify a directory
1539 and new symbolic links are made in that directory
1540 with the same names that the files currently have. The default
1541 suggested for the target directory depends on the value of
1542 `dired-dwim-target', which see."
1543 (interactive "P")
1544 (dired-do-create-files 'symlink (function make-symbolic-link)
1545 "Symlink" arg dired-keep-marker-symlink))
1547 ;;;###autoload
1548 (defun dired-do-hardlink (&optional arg)
1549 "Add names (hard links) current file or all marked (or next ARG) files.
1550 When operating on just the current file, you specify the new name.
1551 When operating on multiple or marked files, you specify a directory
1552 and new hard links are made in that directory
1553 with the same names that the files currently have. The default
1554 suggested for the target directory depends on the value of
1555 `dired-dwim-target', which see."
1556 (interactive "P")
1557 (dired-do-create-files 'hardlink (function dired-hardlink)
1558 "Hardlink" arg dired-keep-marker-hardlink))
1560 (defun dired-hardlink (file newname &optional ok-if-already-exists)
1561 (dired-handle-overwrite newname)
1562 ;; error is caught in -create-files
1563 (add-name-to-file file newname ok-if-already-exists)
1564 ;; Update the link count
1565 (dired-relist-file file))
1567 ;;;###autoload
1568 (defun dired-do-rename (&optional arg)
1569 "Rename current file or all marked (or next ARG) files.
1570 When renaming just the current file, you specify the new name.
1571 When renaming multiple or marked files, you specify a directory.
1572 This command also renames any buffers that are visiting the files.
1573 The default suggested for the target directory depends on the value
1574 of `dired-dwim-target', which see."
1575 (interactive "P")
1576 (dired-do-create-files 'move (function dired-rename-file)
1577 "Move" arg dired-keep-marker-rename "Rename"))
1578 ;;;###end dired-cp.el
1580 ;;; 5K
1581 ;;;###begin dired-re.el
1582 (defun dired-do-create-files-regexp
1583 (file-creator operation arg regexp newname &optional whole-name marker-char)
1584 ;; Create a new file for each marked file using regexps.
1585 ;; FILE-CREATOR and OPERATION as in dired-create-files.
1586 ;; ARG as in dired-get-marked-files.
1587 ;; Matches each marked file against REGEXP and constructs the new
1588 ;; filename from NEWNAME (like in function replace-match).
1589 ;; Optional arg WHOLE-NAME means match/replace the whole file name
1590 ;; instead of only the non-directory part of the file.
1591 ;; Optional arg MARKER-CHAR as in dired-create-files.
1592 (let* ((fn-list (dired-get-marked-files nil arg))
1593 (fn-count (length fn-list))
1594 (operation-prompt (concat operation " `%s' to `%s'?"))
1595 (rename-regexp-help-form (format "\
1596 Type SPC or `y' to %s one match, DEL or `n' to skip to next,
1597 `!' to %s all remaining matches with no more questions."
1598 (downcase operation)
1599 (downcase operation)))
1600 (regexp-name-constructor
1601 ;; Function to construct new filename using REGEXP and NEWNAME:
1602 (if whole-name ; easy (but rare) case
1603 (function
1604 (lambda (from)
1605 (let ((to (dired-string-replace-match regexp from newname))
1606 ;; must bind help-form directly around call to
1607 ;; dired-query
1608 (help-form rename-regexp-help-form))
1609 (if to
1610 (and (dired-query 'rename-regexp-query
1611 operation-prompt
1612 from
1615 (dired-log "%s: %s did not match regexp %s\n"
1616 operation from regexp)))))
1617 ;; not whole-name, replace non-directory part only
1618 (function
1619 (lambda (from)
1620 (let* ((new (dired-string-replace-match
1621 regexp (file-name-nondirectory from) newname))
1622 (to (and new ; nil means there was no match
1623 (expand-file-name new
1624 (file-name-directory from))))
1625 (help-form rename-regexp-help-form))
1626 (if to
1627 (and (dired-query 'rename-regexp-query
1628 operation-prompt
1629 (dired-make-relative from)
1630 (dired-make-relative to))
1632 (dired-log "%s: %s did not match regexp %s\n"
1633 operation (file-name-nondirectory from) regexp)))))))
1634 rename-regexp-query)
1635 (dired-create-files
1636 file-creator operation fn-list regexp-name-constructor marker-char)))
1638 (defun dired-mark-read-regexp (operation)
1639 ;; Prompt user about performing OPERATION.
1640 ;; Read and return list of: regexp newname arg whole-name.
1641 (let* ((whole-name
1642 (equal 0 (prefix-numeric-value current-prefix-arg)))
1643 (arg
1644 (if whole-name nil current-prefix-arg))
1645 (regexp
1646 (dired-read-regexp
1647 (concat (if whole-name "Abs. " "") operation " from (regexp): ")))
1648 (newname
1649 (read-string
1650 (concat (if whole-name "Abs. " "") operation " " regexp " to: "))))
1651 (list regexp newname arg whole-name)))
1653 ;;;###autoload
1654 (defun dired-do-rename-regexp (regexp newname &optional arg whole-name)
1655 "Rename selected files whose names match REGEXP to NEWNAME.
1657 With non-zero prefix argument ARG, the command operates on the next ARG
1658 files. Otherwise, it operates on all the marked files, or the current
1659 file if none are marked.
1661 As each match is found, the user must type a character saying
1662 what to do with it. For directions, type \\[help-command] at that time.
1663 NEWNAME may contain \\=\\<n> or \\& as in `query-replace-regexp'.
1664 REGEXP defaults to the last regexp used.
1666 With a zero prefix arg, renaming by regexp affects the absolute file name.
1667 Normally, only the non-directory part of the file name is used and changed."
1668 (interactive (dired-mark-read-regexp "Rename"))
1669 (dired-do-create-files-regexp
1670 (function dired-rename-file)
1671 "Rename" arg regexp newname whole-name dired-keep-marker-rename))
1673 ;;;###autoload
1674 (defun dired-do-copy-regexp (regexp newname &optional arg whole-name)
1675 "Copy selected files whose names match REGEXP to NEWNAME.
1676 See function `dired-do-rename-regexp' for more info."
1677 (interactive (dired-mark-read-regexp "Copy"))
1678 (let ((dired-recursive-copies nil)) ; No recursive copies.
1679 (dired-do-create-files-regexp
1680 (function dired-copy-file)
1681 (if dired-copy-preserve-time "Copy [-p]" "Copy")
1682 arg regexp newname whole-name dired-keep-marker-copy)))
1684 ;;;###autoload
1685 (defun dired-do-hardlink-regexp (regexp newname &optional arg whole-name)
1686 "Hardlink selected files whose names match REGEXP to NEWNAME.
1687 See function `dired-do-rename-regexp' for more info."
1688 (interactive (dired-mark-read-regexp "HardLink"))
1689 (dired-do-create-files-regexp
1690 (function add-name-to-file)
1691 "HardLink" arg regexp newname whole-name dired-keep-marker-hardlink))
1693 ;;;###autoload
1694 (defun dired-do-symlink-regexp (regexp newname &optional arg whole-name)
1695 "Symlink selected files whose names match REGEXP to NEWNAME.
1696 See function `dired-do-rename-regexp' for more info."
1697 (interactive (dired-mark-read-regexp "SymLink"))
1698 (dired-do-create-files-regexp
1699 (function make-symbolic-link)
1700 "SymLink" arg regexp newname whole-name dired-keep-marker-symlink))
1702 (defun dired-create-files-non-directory
1703 (file-creator basename-constructor operation arg)
1704 ;; Perform FILE-CREATOR on the non-directory part of marked files
1705 ;; using function BASENAME-CONSTRUCTOR, with query for each file.
1706 ;; OPERATION like in dired-create-files, ARG as in dired-get-marked-files.
1707 (let (rename-non-directory-query)
1708 (dired-create-files
1709 file-creator
1710 operation
1711 (dired-get-marked-files nil arg)
1712 (function
1713 (lambda (from)
1714 (let ((to (concat (file-name-directory from)
1715 (funcall basename-constructor
1716 (file-name-nondirectory from)))))
1717 (and (let ((help-form (format "\
1718 Type SPC or `y' to %s one file, DEL or `n' to skip to next,
1719 `!' to %s all remaining matches with no more questions."
1720 (downcase operation)
1721 (downcase operation))))
1722 (dired-query 'rename-non-directory-query
1723 (concat operation " `%s' to `%s'")
1724 (dired-make-relative from)
1725 (dired-make-relative to)))
1726 to))))
1727 dired-keep-marker-rename)))
1729 (defun dired-rename-non-directory (basename-constructor operation arg)
1730 (dired-create-files-non-directory
1731 (function dired-rename-file)
1732 basename-constructor operation arg))
1734 ;;;###autoload
1735 (defun dired-upcase (&optional arg)
1736 "Rename all marked (or next ARG) files to upper case."
1737 (interactive "P")
1738 (dired-rename-non-directory (function upcase) "Rename upcase" arg))
1740 ;;;###autoload
1741 (defun dired-downcase (&optional arg)
1742 "Rename all marked (or next ARG) files to lower case."
1743 (interactive "P")
1744 (dired-rename-non-directory (function downcase) "Rename downcase" arg))
1746 ;;;###end dired-re.el
1748 ;;; 13K
1749 ;;;###begin dired-ins.el
1751 ;;;###autoload
1752 (defun dired-maybe-insert-subdir (dirname &optional
1753 switches no-error-if-not-dir-p)
1754 "Insert this subdirectory into the same dired buffer.
1755 If it is already present, just move to it (type \\[dired-do-redisplay] to refresh),
1756 else inserts it at its natural place (as `ls -lR' would have done).
1757 With a prefix arg, you may edit the ls switches used for this listing.
1758 You can add `R' to the switches to expand the whole tree starting at
1759 this subdirectory.
1760 This function takes some pains to conform to `ls -lR' output.
1762 Dired remembers switches specified with a prefix arg, so that reverting
1763 the buffer will not reset them. However, using `dired-undo' to re-insert
1764 or delete subdirectories can bypass this machinery. Hence, you sometimes
1765 may have to reset some subdirectory switches after a `dired-undo'.
1766 You can reset all subdirectory switches to the default using
1767 \\<dired-mode-map>\\[dired-reset-subdir-switches].
1768 See Info node `(emacs)Subdir switches' for more details."
1769 (interactive
1770 (list (dired-get-filename)
1771 (if current-prefix-arg
1772 (read-string "Switches for listing: "
1773 (or dired-subdir-switches dired-actual-switches)))))
1774 (let ((opoint (point)))
1775 ;; We don't need a marker for opoint as the subdir is always
1776 ;; inserted *after* opoint.
1777 (setq dirname (file-name-as-directory dirname))
1778 (or (and (not switches)
1779 (dired-goto-subdir dirname))
1780 (dired-insert-subdir dirname switches no-error-if-not-dir-p))
1781 ;; Push mark so that it's easy to find back. Do this after the
1782 ;; insert message so that the user sees the `Mark set' message.
1783 (push-mark opoint)))
1785 ;;;###autoload
1786 (defun dired-insert-subdir (dirname &optional switches no-error-if-not-dir-p)
1787 "Insert this subdirectory into the same dired buffer.
1788 If it is already present, overwrites previous entry,
1789 else inserts it at its natural place (as `ls -lR' would have done).
1790 With a prefix arg, you may edit the `ls' switches used for this listing.
1791 You can add `R' to the switches to expand the whole tree starting at
1792 this subdirectory.
1793 This function takes some pains to conform to `ls -lR' output."
1794 ;; NO-ERROR-IF-NOT-DIR-P needed for special filesystems like
1795 ;; Prospero where dired-ls does the right thing, but
1796 ;; file-directory-p has not been redefined.
1797 (interactive
1798 (list (dired-get-filename)
1799 (if current-prefix-arg
1800 (read-string "Switches for listing: "
1801 (or dired-subdir-switches dired-actual-switches)))))
1802 (setq dirname (file-name-as-directory (expand-file-name dirname)))
1803 (or no-error-if-not-dir-p
1804 (file-directory-p dirname)
1805 (error "Attempt to insert a non-directory: %s" dirname))
1806 (let ((elt (assoc dirname dired-subdir-alist))
1807 (cons (assoc-string dirname dired-switches-alist))
1808 (modflag (buffer-modified-p))
1809 (old-switches switches)
1810 switches-have-R mark-alist case-fold-search buffer-read-only)
1811 (and (not switches) cons (setq switches (cdr cons)))
1812 (dired-insert-subdir-validate dirname switches)
1813 ;; case-fold-search is nil now, so we can test for capital `R':
1814 (if (setq switches-have-R (and switches (string-match "R" switches)))
1815 ;; avoid duplicated subdirs
1816 (setq mark-alist (dired-kill-tree dirname t)))
1817 (if elt
1818 ;; If subdir is already present, remove it and remember its marks
1819 (setq mark-alist (nconc (dired-insert-subdir-del elt) mark-alist))
1820 (dired-insert-subdir-newpos dirname)) ; else compute new position
1821 (dired-insert-subdir-doupdate
1822 dirname elt (dired-insert-subdir-doinsert dirname switches))
1823 (when old-switches
1824 (if cons
1825 (setcdr cons switches)
1826 (push (cons dirname switches) dired-switches-alist)))
1827 (when switches-have-R
1828 (dired-build-subdir-alist switches)
1829 (setq switches (dired-replace-in-string "R" "" switches))
1830 (dolist (cur-ass dired-subdir-alist)
1831 (let ((cur-dir (car cur-ass)))
1832 (and (dired-in-this-tree cur-dir dirname)
1833 (let ((cur-cons (assoc-string cur-dir dired-switches-alist)))
1834 (if cur-cons
1835 (setcdr cur-cons switches)
1836 (push (cons cur-dir switches) dired-switches-alist)))))))
1837 (dired-initial-position dirname)
1838 (save-excursion (dired-mark-remembered mark-alist))
1839 (restore-buffer-modified-p modflag)))
1841 ;; This is a separate function for dired-vms.
1842 (defun dired-insert-subdir-validate (dirname &optional switches)
1843 ;; Check that it is valid to insert DIRNAME with SWITCHES.
1844 ;; Signal an error if invalid (e.g. user typed `i' on `..').
1845 (or (dired-in-this-tree dirname (expand-file-name default-directory))
1846 (error "%s: not in this directory tree" dirname))
1847 (let ((real-switches (or switches dired-subdir-switches)))
1848 (when real-switches
1849 (let (case-fold-search)
1850 (mapcar
1851 (function
1852 (lambda (x)
1853 (or (eq (null (string-match x real-switches))
1854 (null (string-match x dired-actual-switches)))
1855 (error
1856 "Can't have dirs with and without -%s switches together" x))))
1857 ;; all switches that make a difference to dired-get-filename:
1858 '("F" "b"))))))
1860 (defun dired-alist-add (dir new-marker)
1861 ;; Add new DIR at NEW-MARKER. Sort alist.
1862 (dired-alist-add-1 dir new-marker)
1863 (dired-alist-sort))
1865 (defun dired-alist-sort ()
1866 ;; Keep the alist sorted on buffer position.
1867 (setq dired-subdir-alist
1868 (sort dired-subdir-alist
1869 (function (lambda (elt1 elt2)
1870 (> (dired-get-subdir-min elt1)
1871 (dired-get-subdir-min elt2)))))))
1873 (defun dired-kill-tree (dirname &optional remember-marks kill-root)
1874 "Kill all proper subdirs of DIRNAME, excluding DIRNAME itself.
1875 Interactively, you can kill DIRNAME as well by using a prefix argument.
1876 In interactive use, the command prompts for DIRNAME.
1878 When called from Lisp, if REMEMBER-MARKS is non-nil, return an alist
1879 of marked files. If KILL-ROOT is non-nil, kill DIRNAME as well."
1880 (interactive "DKill tree below directory: \ni\nP")
1881 (setq dirname (file-name-as-directory (expand-file-name dirname)))
1882 (let ((s-alist dired-subdir-alist) dir m-alist)
1883 (while s-alist
1884 (setq dir (car (car s-alist))
1885 s-alist (cdr s-alist))
1886 (and (or kill-root (not (string-equal dir dirname)))
1887 (dired-in-this-tree dir dirname)
1888 (dired-goto-subdir dir)
1889 (setq m-alist (nconc (dired-kill-subdir remember-marks) m-alist))))
1890 m-alist))
1892 (defun dired-insert-subdir-newpos (new-dir)
1893 ;; Find pos for new subdir, according to tree order.
1894 ;;(goto-char (point-max))
1895 (let ((alist dired-subdir-alist) elt dir pos new-pos)
1896 (while alist
1897 (setq elt (car alist)
1898 alist (cdr alist)
1899 dir (car elt)
1900 pos (dired-get-subdir-min elt))
1901 (if (dired-tree-lessp dir new-dir)
1902 ;; Insert NEW-DIR after DIR
1903 (setq new-pos (dired-get-subdir-max elt)
1904 alist nil)))
1905 (goto-char new-pos))
1906 ;; want a separating newline between subdirs
1907 (or (eobp)
1908 (forward-line -1))
1909 (insert "\n")
1910 (point))
1912 (defun dired-insert-subdir-del (element)
1913 ;; Erase an already present subdir (given by ELEMENT) from buffer.
1914 ;; Move to that buffer position. Return a mark-alist.
1915 (let ((begin-marker (dired-get-subdir-min element)))
1916 (goto-char begin-marker)
1917 ;; Are at beginning of subdir (and inside it!). Now determine its end:
1918 (goto-char (dired-subdir-max))
1919 (or (eobp);; want a separating newline _between_ subdirs:
1920 (forward-char -1))
1921 (prog1
1922 (dired-remember-marks begin-marker (point))
1923 (delete-region begin-marker (point)))))
1925 (defun dired-insert-subdir-doinsert (dirname switches)
1926 ;; Insert ls output after point.
1927 ;; Return the boundary of the inserted text (as list of BEG and END).
1928 (save-excursion
1929 (let ((begin (point)))
1930 (let ((dired-actual-switches
1931 (or switches
1932 dired-subdir-switches
1933 (dired-replace-in-string "R" "" dired-actual-switches))))
1934 (if (equal dirname (car (car (last dired-subdir-alist))))
1935 ;; If doing the top level directory of the buffer,
1936 ;; redo it as specified in dired-directory.
1937 (dired-readin-insert)
1938 (dired-insert-directory dirname dired-actual-switches nil nil t)))
1939 (list begin (point)))))
1941 (defun dired-insert-subdir-doupdate (dirname elt beg-end)
1942 ;; Point is at the correct subdir alist position for ELT,
1943 ;; BEG-END is the subdir-region (as list of begin and end).
1944 (if elt ; subdir was already present
1945 ;; update its position (should actually be unchanged)
1946 (set-marker (dired-get-subdir-min elt) (point-marker))
1947 (dired-alist-add dirname (point-marker)))
1948 ;; The hook may depend on the subdir-alist containing the just
1949 ;; inserted subdir, so run it after dired-alist-add:
1950 (if dired-after-readin-hook
1951 (save-excursion
1952 (let ((begin (nth 0 beg-end))
1953 (end (nth 1 beg-end)))
1954 (goto-char begin)
1955 (save-restriction
1956 (narrow-to-region begin end)
1957 ;; hook may add or delete lines, but the subdir boundary
1958 ;; marker floats
1959 (run-hooks 'dired-after-readin-hook))))))
1961 (defun dired-tree-lessp (dir1 dir2)
1962 ;; Lexicographic order on file name components, like `ls -lR':
1963 ;; DIR1 < DIR2 iff DIR1 comes *before* DIR2 in an `ls -lR' listing,
1964 ;; i.e., iff DIR1 is a (grand)parent dir of DIR2,
1965 ;; or DIR1 and DIR2 are in the same parentdir and their last
1966 ;; components are string-lessp.
1967 ;; Thus ("/usr/" "/usr/bin") and ("/usr/a/" "/usr/b/") are tree-lessp.
1968 ;; string-lessp could arguably be replaced by file-newer-than-file-p
1969 ;; if dired-actual-switches contained `t'.
1970 (setq dir1 (file-name-as-directory dir1)
1971 dir2 (file-name-as-directory dir2))
1972 (let ((components-1 (dired-split "/" dir1))
1973 (components-2 (dired-split "/" dir2)))
1974 (while (and components-1
1975 components-2
1976 (equal (car components-1) (car components-2)))
1977 (setq components-1 (cdr components-1)
1978 components-2 (cdr components-2)))
1979 (let ((c1 (car components-1))
1980 (c2 (car components-2)))
1982 (cond ((and c1 c2)
1983 (string-lessp c1 c2))
1984 ((and (null c1) (null c2))
1985 nil) ; they are equal, not lessp
1986 ((null c1) ; c2 is a subdir of c1: c1<c2
1988 ((null c2) ; c1 is a subdir of c2: c1>c2
1989 nil)
1990 (t (error "This can't happen"))))))
1992 ;; There should be a builtin split function - inverse to mapconcat.
1993 (defun dired-split (pat str &optional limit)
1994 "Splitting on regexp PAT, turn string STR into a list of substrings.
1995 Optional third arg LIMIT (>= 1) is a limit to the length of the
1996 resulting list.
1997 Thus, if SEP is a regexp that only matches itself,
1999 (mapconcat 'identity (dired-split SEP STRING) SEP)
2001 is always equal to STRING."
2002 (let* ((start (string-match pat str))
2003 (result (list (substring str 0 start)))
2004 (count 1)
2005 (end (if start (match-end 0))))
2006 (if end ; else nothing left
2007 (while (and (or (not (integerp limit))
2008 (< count limit))
2009 (string-match pat str end))
2010 (setq start (match-beginning 0)
2011 count (1+ count)
2012 result (cons (substring str end start) result)
2013 end (match-end 0)
2014 start end)
2016 (if (and (or (not (integerp limit))
2017 (< count limit))
2018 end) ; else nothing left
2019 (setq result
2020 (cons (substring str end) result)))
2021 (nreverse result)))
2023 ;;; moving by subdirectories
2025 ;;;###autoload
2026 (defun dired-prev-subdir (arg &optional no-error-if-not-found no-skip)
2027 "Go to previous subdirectory, regardless of level.
2028 When called interactively and not on a subdir line, go to this subdir's line."
2029 ;;(interactive "p")
2030 (interactive
2031 (list (if current-prefix-arg
2032 (prefix-numeric-value current-prefix-arg)
2033 ;; if on subdir start already, don't stay there!
2034 (if (dired-get-subdir) 1 0))))
2035 (dired-next-subdir (- arg) no-error-if-not-found no-skip))
2037 (defun dired-subdir-min ()
2038 (save-excursion
2039 (if (not (dired-prev-subdir 0 t t))
2040 (error "Not in a subdir!")
2041 (point))))
2043 ;;;###autoload
2044 (defun dired-goto-subdir (dir)
2045 "Go to end of header line of DIR in this dired buffer.
2046 Return value of point on success, otherwise return nil.
2047 The next char is either \\n, or \\r if DIR is hidden."
2048 (interactive
2049 (prog1 ; let push-mark display its message
2050 (list (expand-file-name
2051 (completing-read "Goto in situ directory: " ; prompt
2052 dired-subdir-alist ; table
2053 nil ; predicate
2054 t ; require-match
2055 (dired-current-directory))))
2056 (push-mark)))
2057 (setq dir (file-name-as-directory dir))
2058 (let ((elt (assoc dir dired-subdir-alist)))
2059 (and elt
2060 (goto-char (dired-get-subdir-min elt))
2061 ;; dired-subdir-hidden-p and dired-add-entry depend on point being
2062 ;; at either \r or \n after this function succeeds.
2063 (progn (skip-chars-forward "^\r\n")
2064 (point)))))
2066 ;;;###autoload
2067 (defun dired-mark-subdir-files ()
2068 "Mark all files except `.' and `..' in current subdirectory.
2069 If the Dired buffer shows multiple directories, this command
2070 marks the files listed in the subdirectory that point is in."
2071 (interactive)
2072 (let ((p-min (dired-subdir-min)))
2073 (dired-mark-files-in-region p-min (dired-subdir-max))))
2075 ;;;###autoload
2076 (defun dired-kill-subdir (&optional remember-marks)
2077 "Remove all lines of current subdirectory.
2078 Lower levels are unaffected."
2079 ;; With optional REMEMBER-MARKS, return a mark-alist.
2080 (interactive)
2081 (let* ((beg (dired-subdir-min))
2082 (end (dired-subdir-max))
2083 (modflag (buffer-modified-p))
2084 (cur-dir (dired-current-directory))
2085 (cons (assoc-string cur-dir dired-switches-alist))
2086 buffer-read-only)
2087 (if (equal cur-dir default-directory)
2088 (error "Attempt to kill top level directory"))
2089 (prog1
2090 (if remember-marks (dired-remember-marks beg end))
2091 (delete-region beg end)
2092 (if (eobp) ; don't leave final blank line
2093 (delete-char -1))
2094 (dired-unsubdir cur-dir)
2095 (when cons
2096 (setq dired-switches-alist (delete cons dired-switches-alist)))
2097 (restore-buffer-modified-p modflag))))
2099 (defun dired-unsubdir (dir)
2100 ;; Remove DIR from the alist
2101 (setq dired-subdir-alist
2102 (delq (assoc dir dired-subdir-alist) dired-subdir-alist)))
2104 ;;;###autoload
2105 (defun dired-tree-up (arg)
2106 "Go up ARG levels in the dired tree."
2107 (interactive "p")
2108 (let ((dir (dired-current-directory)))
2109 (while (>= arg 1)
2110 (setq arg (1- arg)
2111 dir (file-name-directory (directory-file-name dir))))
2112 ;;(setq dir (expand-file-name dir))
2113 (or (dired-goto-subdir dir)
2114 (error "Cannot go up to %s - not in this tree" dir))))
2116 ;;;###autoload
2117 (defun dired-tree-down ()
2118 "Go down in the dired tree."
2119 (interactive)
2120 (let ((dir (dired-current-directory)) ; has slash
2121 pos case-fold-search) ; filenames are case sensitive
2122 (let ((rest (reverse dired-subdir-alist)) elt)
2123 (while rest
2124 (setq elt (car rest)
2125 rest (cdr rest))
2126 (if (dired-in-this-tree (directory-file-name (car elt)) dir)
2127 (setq rest nil
2128 pos (dired-goto-subdir (car elt))))))
2129 (if pos
2130 (goto-char pos)
2131 (error "At the bottom"))))
2133 ;;; hiding
2135 (defun dired-unhide-subdir ()
2136 (let (buffer-read-only)
2137 (subst-char-in-region (dired-subdir-min) (dired-subdir-max) ?\r ?\n)))
2139 (defun dired-hide-check ()
2140 (or selective-display
2141 (error "selective-display must be t for subdir hiding to work!")))
2143 (defun dired-subdir-hidden-p (dir)
2144 (and selective-display
2145 (save-excursion
2146 (dired-goto-subdir dir)
2147 (looking-at "\r"))))
2149 ;;;###autoload
2150 (defun dired-hide-subdir (arg)
2151 "Hide or unhide the current subdirectory and move to next directory.
2152 Optional prefix arg is a repeat factor.
2153 Use \\[dired-hide-all] to (un)hide all directories."
2154 (interactive "p")
2155 (dired-hide-check)
2156 (let ((modflag (buffer-modified-p)))
2157 (while (>= (setq arg (1- arg)) 0)
2158 (let* ((cur-dir (dired-current-directory))
2159 (hidden-p (dired-subdir-hidden-p cur-dir))
2160 (elt (assoc cur-dir dired-subdir-alist))
2161 (end-pos (1- (dired-get-subdir-max elt)))
2162 buffer-read-only)
2163 ;; keep header line visible, hide rest
2164 (goto-char (dired-get-subdir-min elt))
2165 (skip-chars-forward "^\n\r")
2166 (if hidden-p
2167 (subst-char-in-region (point) end-pos ?\r ?\n)
2168 (subst-char-in-region (point) end-pos ?\n ?\r)))
2169 (dired-next-subdir 1 t))
2170 (restore-buffer-modified-p modflag)))
2172 ;;;###autoload
2173 (defun dired-hide-all (arg)
2174 "Hide all subdirectories, leaving only their header lines.
2175 If there is already something hidden, make everything visible again.
2176 Use \\[dired-hide-subdir] to (un)hide a particular subdirectory."
2177 (interactive "P")
2178 (dired-hide-check)
2179 (let ((modflag (buffer-modified-p))
2180 buffer-read-only)
2181 (if (save-excursion
2182 (goto-char (point-min))
2183 (search-forward "\r" nil t))
2184 ;; unhide - bombs on \r in filenames
2185 (subst-char-in-region (point-min) (point-max) ?\r ?\n)
2186 ;; hide
2187 (let ((pos (point-max)) ; pos of end of last directory
2188 (alist dired-subdir-alist))
2189 (while alist ; while there are dirs before pos
2190 (subst-char-in-region (dired-get-subdir-min (car alist)) ; pos of prev dir
2191 (save-excursion
2192 (goto-char pos) ; current dir
2193 ;; we're somewhere on current dir's line
2194 (forward-line -1)
2195 (point))
2196 ?\n ?\r)
2197 (setq pos (dired-get-subdir-min (car alist))) ; prev dir gets current dir
2198 (setq alist (cdr alist)))))
2199 (restore-buffer-modified-p modflag)))
2201 ;;;###end dired-ins.el
2204 ;; Functions for searching in tags style among marked files.
2206 ;;;###autoload
2207 (defun dired-do-search (regexp)
2208 "Search through all marked files for a match for REGEXP.
2209 Stops when a match is found.
2210 To continue searching for next match, use command \\[tags-loop-continue]."
2211 (interactive "sSearch marked files (regexp): ")
2212 (tags-search regexp '(dired-get-marked-files nil nil 'dired-nondirectory-p)))
2214 ;;;###autoload
2215 (defun dired-do-query-replace-regexp (from to &optional delimited)
2216 "Do `query-replace-regexp' of FROM with TO, on all marked files.
2217 Third arg DELIMITED (prefix arg) means replace only word-delimited matches.
2218 If you exit (\\[keyboard-quit], RET or q), you can resume the query replace
2219 with the command \\[tags-loop-continue]."
2220 (interactive
2221 (let ((common
2222 (query-replace-read-args
2223 "Query replace regexp in marked files" t t)))
2224 (list (nth 0 common) (nth 1 common) (nth 2 common))))
2225 (dolist (file (dired-get-marked-files nil nil 'dired-nondirectory-p))
2226 (let ((buffer (get-file-buffer file)))
2227 (if (and buffer (with-current-buffer buffer
2228 buffer-read-only))
2229 (error "File `%s' is visited read-only" file))))
2230 (tags-query-replace from to delimited
2231 '(dired-get-marked-files nil nil 'dired-nondirectory-p)))
2233 (defun dired-nondirectory-p (file)
2234 (not (file-directory-p file)))
2236 ;;;###autoload
2237 (defun dired-show-file-type (file &optional deref-symlinks)
2238 "Print the type of FILE, according to the `file' command.
2239 If FILE is a symbolic link and the optional argument DEREF-SYMLINKS is
2240 true then the type of the file linked to by FILE is printed instead."
2241 (interactive (list (dired-get-filename t) current-prefix-arg))
2242 (with-temp-buffer
2243 (if deref-symlinks
2244 (call-process "file" nil t t "-L" "--" file)
2245 (call-process "file" nil t t "--" file))
2246 (when (bolp)
2247 (backward-delete-char 1))
2248 (message "%s" (buffer-string))))
2250 (provide 'dired-aux)
2252 ;;; arch-tag: 4b508de9-a153-423d-8d3f-a1bbd86f4f60
2253 ;;; dired-aux.el ends here