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