Warn against using `length' to compute display width of a string.
[emacs.git] / lisp / dired-aux.el
blobd6a4a7816d60efea76a7d4ca242b9d54520ad4aa
1 ;;; dired-aux.el --- less commonly used parts of dired
3 ;; Copyright (C) 1985-1986, 1992, 1994, 1998, 2000-2012
4 ;; Free Software Foundation, Inc.
6 ;; Author: Sebastian Kremer <sk@thp.uni-koeln.de>.
7 ;; Maintainer: FSF
8 ;; Keywords: files
9 ;; Package: emacs
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26 ;;; Commentary:
28 ;; The parts of dired mode not normally used. This is a space-saving hack
29 ;; to avoid having to load a large mode when all that's wanted are a few
30 ;; functions.
32 ;; Rewritten in 1990/1991 to add tree features, file marking and
33 ;; sorting by Sebastian Kremer <sk@thp.uni-koeln.de>.
34 ;; Finished up by rms in 1992.
36 ;;; Code:
38 ;; We need macros in dired.el to compile properly,
39 ;; and we call subroutines in it too.
40 (require 'dired)
42 (defvar dired-create-files-failures nil
43 "Variable where `dired-create-files' records failing file names.
44 Functions that operate recursively can store additional names
45 into this list; they also should call `dired-log' to log the errors.")
47 ;;; 15K
48 ;;;###begin dired-cmd.el
49 ;; Diffing and compressing
51 (defconst dired-star-subst-regexp "\\(^\\|[ \t]\\)\\*\\([ \t]\\|$\\)")
52 (defconst dired-quark-subst-regexp "\\(^\\|[ \t]\\)\\?\\([ \t]\\|$\\)")
54 ;;;###autoload
55 (defun dired-diff (file &optional switches)
56 "Compare file at point with file FILE using `diff'.
57 FILE defaults to the file at the mark. (That's the mark set by
58 \\[set-mark-command], not by Dired's \\[dired-mark] command.)
59 The prompted-for FILE is the first file given to `diff'.
60 With prefix arg, prompt for second argument SWITCHES,
61 which is the string of command switches for `diff'."
62 (interactive
63 (let* ((current (dired-get-filename t))
64 ;; Get the file at the mark.
65 (file-at-mark (if (mark t)
66 (save-excursion (goto-char (mark t))
67 (dired-get-filename t t))))
68 ;; Use it as default if it's not the same as the current file,
69 ;; and the target dir is the current dir or the mark is active.
70 (default (if (and (not (equal file-at-mark current))
71 (or (equal (dired-dwim-target-directory)
72 (dired-current-directory))
73 mark-active))
74 file-at-mark))
75 (target-dir (if default
76 (dired-current-directory)
77 (dired-dwim-target-directory)))
78 (defaults (dired-dwim-target-defaults (list current) target-dir)))
79 (require 'diff)
80 (list
81 (minibuffer-with-setup-hook
82 (lambda ()
83 (set (make-local-variable 'minibuffer-default-add-function) nil)
84 (setq minibuffer-default defaults))
85 (read-file-name
86 (format "Diff %s with%s: " current
87 (if default (format " (default %s)" default) ""))
88 target-dir default t))
89 (if current-prefix-arg
90 (read-string "Options for diff: "
91 (if (stringp diff-switches)
92 diff-switches
93 (mapconcat 'identity diff-switches " ")))))))
94 (let ((current (dired-get-filename t)))
95 (when (or (equal (expand-file-name file)
96 (expand-file-name current))
97 (and (file-directory-p file)
98 (equal (expand-file-name current file)
99 (expand-file-name current))))
100 (error "Attempt to compare the file to itself"))
101 (diff file current switches)))
103 ;;;###autoload
104 (defun dired-backup-diff (&optional switches)
105 "Diff this file with its backup file or vice versa.
106 Uses the latest backup, if there are several numerical backups.
107 If this file is a backup, diff it with its original.
108 The backup file is the first file given to `diff'.
109 With prefix arg, prompt for argument SWITCHES which is options for `diff'."
110 (interactive
111 (if current-prefix-arg
112 (list (read-string "Options for diff: "
113 (if (stringp diff-switches)
114 diff-switches
115 (mapconcat 'identity diff-switches " "))))
116 nil))
117 (diff-backup (dired-get-filename) switches))
119 ;;;###autoload
120 (defun dired-compare-directories (dir2 predicate)
121 "Mark files with different file attributes in two dired buffers.
122 Compare file attributes of files in the current directory
123 with file attributes in directory DIR2 using PREDICATE on pairs of files
124 with the same name. Mark files for which PREDICATE returns non-nil.
125 Mark files with different names if PREDICATE is nil (or interactively
126 with empty input at the predicate prompt).
128 PREDICATE is a Lisp expression that can refer to the following variables:
130 size1, size2 - file size in bytes
131 mtime1, mtime2 - last modification time in seconds, as a float
132 fa1, fa2 - list of file attributes
133 returned by function `file-attributes'
135 where 1 refers to attribute of file in the current dired buffer
136 and 2 to attribute of file in second dired buffer.
138 Examples of PREDICATE:
140 (> mtime1 mtime2) - mark newer files
141 (not (= size1 size2)) - mark files with different sizes
142 (not (string= (nth 8 fa1) (nth 8 fa2))) - mark files with different modes
143 (not (and (= (nth 2 fa1) (nth 2 fa2)) - mark files with different UID
144 (= (nth 3 fa1) (nth 3 fa2)))) and GID."
145 (interactive
146 (list
147 (let* ((target-dir (dired-dwim-target-directory))
148 (defaults (dired-dwim-target-defaults nil target-dir)))
149 (minibuffer-with-setup-hook
150 (lambda ()
151 (set (make-local-variable 'minibuffer-default-add-function) nil)
152 (setq minibuffer-default defaults))
153 (read-directory-name (format "Compare %s with: "
154 (dired-current-directory))
155 target-dir target-dir t)))
156 (read-from-minibuffer "Mark if (lisp expr or RET): " nil nil t nil "nil")))
157 (let* ((dir1 (dired-current-directory))
158 (file-alist1 (dired-files-attributes dir1))
159 (file-alist2 (dired-files-attributes dir2))
160 file-list1 file-list2)
161 (setq file-alist1 (delq (assoc "." file-alist1) file-alist1))
162 (setq file-alist1 (delq (assoc ".." file-alist1) file-alist1))
163 (setq file-alist2 (delq (assoc "." file-alist2) file-alist2))
164 (setq file-alist2 (delq (assoc ".." file-alist2) file-alist2))
165 (setq file-list1 (mapcar
166 'cadr
167 (dired-file-set-difference
168 file-alist1 file-alist2
169 predicate))
170 file-list2 (mapcar
171 'cadr
172 (dired-file-set-difference
173 file-alist2 file-alist1
174 predicate)))
175 (dired-fun-in-all-buffers
176 dir1 nil
177 (lambda ()
178 (dired-mark-if
179 (member (dired-get-filename nil t) file-list1) nil)))
180 (dired-fun-in-all-buffers
181 dir2 nil
182 (lambda ()
183 (dired-mark-if
184 (member (dired-get-filename nil t) file-list2) nil)))
185 (message "Marked in dir1: %s files, in dir2: %s files"
186 (length file-list1)
187 (length file-list2))))
189 (defun dired-file-set-difference (list1 list2 predicate)
190 "Combine LIST1 and LIST2 using a set-difference operation.
191 The result list contains all file items that appear in LIST1 but not LIST2.
192 This is a non-destructive function; it makes a copy of the data if necessary
193 to avoid corrupting the original LIST1 and LIST2.
194 PREDICATE (see `dired-compare-directories') is an additional match
195 condition. Two file items are considered to match if they are equal
196 *and* PREDICATE evaluates to t."
197 (if (or (null list1) (null list2))
198 list1
199 (let (res)
200 (dolist (file1 list1)
201 (unless (let ((list list2))
202 (while (and list
203 (not (let* ((file2 (car list))
204 (fa1 (car (cddr file1)))
205 (fa2 (car (cddr file2)))
206 (size1 (nth 7 fa1))
207 (size2 (nth 7 fa2))
208 (mtime1 (float-time (nth 5 fa1)))
209 (mtime2 (float-time (nth 5 fa2))))
210 (and
211 (equal (car file1) (car file2))
212 (not (eval predicate))))))
213 (setq list (cdr list)))
214 list)
215 (setq res (cons file1 res))))
216 (nreverse res))))
218 (defun dired-files-attributes (dir)
219 "Return a list of all file names and attributes from DIR.
220 List has a form of (file-name full-file-name (attribute-list))."
221 (mapcar
222 (lambda (file-name)
223 (let ((full-file-name (expand-file-name file-name dir)))
224 (list file-name
225 full-file-name
226 (file-attributes full-file-name))))
227 (directory-files dir)))
229 ;;; Change file attributes
231 (defun dired-do-chxxx (attribute-name program op-symbol arg)
232 ;; Change file attributes (group, owner, timestamp) of marked files and
233 ;; refresh their file lines.
234 ;; ATTRIBUTE-NAME is a string describing the attribute to the user.
235 ;; PROGRAM is the program used to change the attribute.
236 ;; OP-SYMBOL is the type of operation (for use in `dired-mark-pop-up').
237 ;; ARG describes which files to use, as in `dired-get-marked-files'.
238 (let* ((files (dired-get-marked-files t arg))
239 (default (and (eq op-symbol 'touch)
240 (stringp (car files))
241 (format-time-string "%Y%m%d%H%M.%S"
242 (nth 5 (file-attributes (car files))))))
243 (prompt (concat "Change " attribute-name " of %s to"
244 (if (eq op-symbol 'touch)
245 " (default now): "
246 ": ")))
247 (new-attribute (dired-mark-read-string prompt nil op-symbol
248 arg files default))
249 (operation (concat program " " new-attribute))
250 failures)
251 (setq failures
252 (dired-bunch-files 10000
253 (function dired-check-process)
254 (append
255 (list operation program)
256 (unless (string-equal new-attribute "")
257 (if (eq op-symbol 'touch)
258 (list "-t" new-attribute)
259 (list new-attribute)))
260 (if (string-match "gnu" system-configuration)
261 '("--") nil))
262 files))
263 (dired-do-redisplay arg);; moves point if ARG is an integer
264 (if failures
265 (dired-log-summary
266 (format "%s: error" operation)
267 nil))))
269 ;;;###autoload
270 (defun dired-do-chmod (&optional arg)
271 "Change the mode of the marked (or next ARG) files.
272 Symbolic modes like `g+w' are allowed."
273 (interactive "P")
274 (let* ((files (dired-get-marked-files t arg))
275 (modestr (and (stringp (car files))
276 (nth 8 (file-attributes (car files)))))
277 (default
278 (and (stringp modestr)
279 (string-match "^.\\(...\\)\\(...\\)\\(...\\)$" modestr)
280 (replace-regexp-in-string
281 "-" ""
282 (format "u=%s,g=%s,o=%s"
283 (match-string 1 modestr)
284 (match-string 2 modestr)
285 (match-string 3 modestr)))))
286 (modes (dired-mark-read-string
287 "Change mode of %s to: "
288 nil 'chmod arg files default))
289 num-modes)
290 (cond ((equal modes "")
291 ;; We used to treat empty input as DEFAULT, but that is not
292 ;; such a good idea (Bug#9361).
293 (error "No file mode specified"))
294 ((string-match "^[0-7]+" modes)
295 (setq num-modes (string-to-number modes 8))))
297 (dolist (file files)
298 (set-file-modes
299 file
300 (if num-modes num-modes
301 (file-modes-symbolic-to-number modes (file-modes file)))))
302 (dired-do-redisplay arg)))
304 ;;;###autoload
305 (defun dired-do-chgrp (&optional arg)
306 "Change the group of the marked (or next ARG) files."
307 (interactive "P")
308 (if (memq system-type '(ms-dos windows-nt))
309 (error "chgrp not supported on this system"))
310 (dired-do-chxxx "Group" "chgrp" 'chgrp arg))
312 ;;;###autoload
313 (defun dired-do-chown (&optional arg)
314 "Change the owner of the marked (or next ARG) files."
315 (interactive "P")
316 (if (memq system-type '(ms-dos windows-nt))
317 (error "chown not supported on this system"))
318 (dired-do-chxxx "Owner" dired-chown-program 'chown arg))
320 ;;;###autoload
321 (defun dired-do-touch (&optional arg)
322 "Change the timestamp of the marked (or next ARG) files.
323 This calls touch."
324 (interactive "P")
325 (dired-do-chxxx "Timestamp" dired-touch-program 'touch arg))
327 ;; Process all the files in FILES in batches of a convenient size,
328 ;; by means of (FUNCALL FUNCTION ARGS... SOME-FILES...).
329 ;; Batches are chosen to need less than MAX chars for the file names,
330 ;; allowing 3 extra characters of separator per file name.
331 (defun dired-bunch-files (max function args files)
332 (let (pending
333 past
334 (pending-length 0)
335 failures)
336 ;; Accumulate files as long as they fit in MAX chars,
337 ;; then process the ones accumulated so far.
338 (while files
339 (let* ((thisfile (car files))
340 (thislength (+ (length thisfile) 3))
341 (rest (cdr files)))
342 ;; If we have at least 1 pending file
343 ;; and this file won't fit in the length limit, process now.
344 (if (and pending (> (+ thislength pending-length) max))
345 (setq pending (nreverse pending)
346 ;; The elements of PENDING are now in forward order.
347 ;; Do the operation and record failures.
348 failures (nconc (apply function (append args pending))
349 failures)
350 ;; Transfer the elements of PENDING onto PAST
351 ;; and clear it out. Now PAST contains the first N files
352 ;; specified (for some N), and FILES contains the rest.
353 past (nconc past pending)
354 pending nil
355 pending-length 0))
356 ;; Do (setq pending (cons thisfile pending))
357 ;; but reuse the cons that was in `files'.
358 (setcdr files pending)
359 (setq pending files)
360 (setq pending-length (+ thislength pending-length))
361 (setq files rest)))
362 (setq pending (nreverse pending))
363 (prog1
364 (nconc (apply function (append args pending))
365 failures)
366 ;; Now the original list FILES has been put back as it was.
367 (nconc past pending))))
369 ;;;###autoload
370 (defun dired-do-print (&optional arg)
371 "Print the marked (or next ARG) files.
372 Uses the shell command coming from variables `lpr-command' and
373 `lpr-switches' as default."
374 (interactive "P")
375 (let* ((file-list (dired-get-marked-files t arg))
376 (command (dired-mark-read-string
377 "Print %s with: "
378 (mapconcat 'identity
379 (cons lpr-command
380 (if (stringp lpr-switches)
381 (list lpr-switches)
382 lpr-switches))
383 " ")
384 'print arg file-list)))
385 (dired-run-shell-command (dired-shell-stuff-it command file-list nil))))
387 (defun dired-mark-read-string (prompt initial op-symbol arg files
388 &optional default-value)
389 "Read args for a Dired marked-files command, prompting with PROMPT.
390 Return the user input (a string).
392 INITIAL, if non-nil, is the initial minibuffer input.
393 OP-SYMBOL is an operation symbol (see `dired-no-confirm').
394 ARG is normally the prefix argument for the calling command.
395 FILES should be a list of file names.
397 DEFAULT-VALUE, if non-nil, should be a \"standard\" value or list
398 of such values, available via history commands. Note that if the
399 user enters empty input, this function returns the empty string,
400 not DEFAULT-VALUE."
401 (dired-mark-pop-up nil op-symbol files
402 'read-from-minibuffer
403 (format prompt (dired-mark-prompt arg files))
404 initial nil nil nil default-value))
406 ;;; Cleaning a directory: flagging some backups for deletion.
408 (defvar dired-file-version-alist)
410 ;;;###autoload
411 (defun dired-clean-directory (keep)
412 "Flag numerical backups for deletion.
413 Spares `dired-kept-versions' latest versions, and `kept-old-versions' oldest.
414 Positive prefix arg KEEP overrides `dired-kept-versions';
415 Negative prefix arg KEEP overrides `kept-old-versions' with KEEP made positive.
417 To clear the flags on these files, you can use \\[dired-flag-backup-files]
418 with a prefix argument."
419 (interactive "P")
420 (setq keep (if keep (prefix-numeric-value keep) dired-kept-versions))
421 (let ((early-retention (if (< keep 0) (- keep) kept-old-versions))
422 (late-retention (if (<= keep 0) dired-kept-versions keep))
423 (dired-file-version-alist ()))
424 (message "Cleaning numerical backups (keeping %d late, %d old)..."
425 late-retention early-retention)
426 ;; Look at each file.
427 ;; If the file has numeric backup versions,
428 ;; put on dired-file-version-alist an element of the form
429 ;; (FILENAME . VERSION-NUMBER-LIST)
430 (dired-map-dired-file-lines (function dired-collect-file-versions))
431 ;; Sort each VERSION-NUMBER-LIST,
432 ;; and remove the versions not to be deleted.
433 (let ((fval dired-file-version-alist))
434 (while fval
435 (let* ((sorted-v-list (cons 'q (sort (cdr (car fval)) '<)))
436 (v-count (length sorted-v-list)))
437 (if (> v-count (+ early-retention late-retention))
438 (rplacd (nthcdr early-retention sorted-v-list)
439 (nthcdr (- v-count late-retention)
440 sorted-v-list)))
441 (rplacd (car fval)
442 (cdr sorted-v-list)))
443 (setq fval (cdr fval))))
444 ;; Look at each file. If it is a numeric backup file,
445 ;; find it in a VERSION-NUMBER-LIST and maybe flag it for deletion.
446 (dired-map-dired-file-lines (function dired-trample-file-versions))
447 (message "Cleaning numerical backups...done")))
449 ;;; Subroutines of dired-clean-directory.
451 (defun dired-map-dired-file-lines (fun)
452 ;; Perform FUN with point at the end of each non-directory line.
453 ;; FUN takes one argument, the absolute filename.
454 (save-excursion
455 (let (file buffer-read-only)
456 (goto-char (point-min))
457 (while (not (eobp))
458 (save-excursion
459 (and (not (looking-at dired-re-dir))
460 (not (eolp))
461 (setq file (dired-get-filename nil t)) ; nil on non-file
462 (progn (end-of-line)
463 (funcall fun file))))
464 (forward-line 1)))))
466 (defvar backup-extract-version-start) ; used in backup-extract-version
468 (defun dired-collect-file-versions (fn)
469 (let ((fn (file-name-sans-versions fn)))
470 ;; Only do work if this file is not already in the alist.
471 (if (assoc fn dired-file-version-alist)
473 ;; If it looks like file FN has versions, return a list of the versions.
474 ;;That is a list of strings which are file names.
475 ;;The caller may want to flag some of these files for deletion.
476 (let* ((base-versions
477 (concat (file-name-nondirectory fn) ".~"))
478 (backup-extract-version-start (length base-versions))
479 (possibilities (file-name-all-completions
480 base-versions
481 (file-name-directory fn)))
482 (versions (mapcar 'backup-extract-version possibilities)))
483 (if versions
484 (setq dired-file-version-alist
485 (cons (cons fn versions)
486 dired-file-version-alist)))))))
488 (defun dired-trample-file-versions (fn)
489 (let* ((start-vn (string-match "\\.~[0-9]+~$" fn))
490 base-version-list)
491 (and start-vn
492 (setq base-version-list ; there was a base version to which
493 (assoc (substring fn 0 start-vn) ; this looks like a
494 dired-file-version-alist)) ; subversion
495 (not (memq (string-to-number (substring fn (+ 2 start-vn)))
496 base-version-list)) ; this one doesn't make the cut
497 (progn (beginning-of-line)
498 (delete-char 1)
499 (insert dired-del-marker)))))
501 ;;; Shell commands
503 (declare-function mailcap-file-default-commands "mailcap" (files))
505 (defun minibuffer-default-add-dired-shell-commands ()
506 "Return a list of all commands associated with current dired files.
507 This function is used to add all related commands retrieved by `mailcap'
508 to the end of the list of defaults just after the default value."
509 (interactive)
510 (let ((commands (and (boundp 'files) (require 'mailcap nil t)
511 (mailcap-file-default-commands files))))
512 (if (listp minibuffer-default)
513 (append minibuffer-default commands)
514 (cons minibuffer-default commands))))
516 ;; This is an extra function so that you can redefine it, e.g., to use gmhist.
517 (defun dired-read-shell-command (prompt arg files)
518 "Read a dired shell command.
519 PROMPT should be a format string with one \"%s\" format sequence,
520 which is replaced by the value returned by `dired-mark-prompt',
521 with ARG and FILES as its arguments. FILES should be a list of
522 file names. The result is used as the prompt.
524 This normally reads using `read-shell-command', but if the
525 `dired-x' package is loaded, use `dired-guess-shell-command' to
526 offer a smarter default choice of shell command."
527 (minibuffer-with-setup-hook
528 (lambda ()
529 (set (make-local-variable 'minibuffer-default-add-function)
530 'minibuffer-default-add-dired-shell-commands))
531 (setq prompt (format prompt (dired-mark-prompt arg files)))
532 (if (functionp 'dired-guess-shell-command)
533 (dired-mark-pop-up nil 'shell files
534 'dired-guess-shell-command prompt files)
535 (dired-mark-pop-up nil 'shell files
536 'read-shell-command prompt nil nil))))
538 ;;;###autoload
539 (defun dired-do-async-shell-command (command &optional arg file-list)
540 "Run a shell command COMMAND on the marked files asynchronously.
542 Like `dired-do-shell-command' but if COMMAND doesn't end in ampersand,
543 adds `* &' surrounded by whitespace and executes the command asynchronously.
544 The output appears in the buffer `*Async Shell Command*'."
545 (interactive
546 (let ((files (dired-get-marked-files t current-prefix-arg)))
547 (list
548 ;; Want to give feedback whether this file or marked files are used:
549 (dired-read-shell-command "& on %s: " current-prefix-arg files)
550 current-prefix-arg
551 files)))
552 (unless (string-match "[*?][ \t]*\\'" command)
553 (setq command (concat command " *")))
554 (unless (string-match "&[ \t]*\\'" command)
555 (setq command (concat command " &")))
556 (dired-do-shell-command command arg file-list))
558 ;; The in-background argument is only needed in Emacs 18 where
559 ;; shell-command doesn't understand an appended ampersand `&'.
560 ;;;###autoload
561 (defun dired-do-shell-command (command &optional arg file-list)
562 "Run a shell command COMMAND on the marked files.
563 If no files are marked or a specific numeric prefix arg is given,
564 the next ARG files are used. Just \\[universal-argument] means the current file.
565 The prompt mentions the file(s) or the marker, as appropriate.
567 If there is a `*' in COMMAND, surrounded by whitespace, this runs
568 COMMAND just once with the entire file list substituted there.
570 If there is no `*', but there is a `?' in COMMAND, surrounded by
571 whitespace, this runs COMMAND on each file individually with the
572 file name substituted for `?'.
574 Otherwise, this runs COMMAND on each file individually with the
575 file name added at the end of COMMAND (separated by a space).
577 `*' and `?' when not surrounded by whitespace have no special
578 significance for `dired-do-shell-command', and are passed through
579 normally to the shell, but you must confirm first.
581 If you want to use `*' as a shell wildcard with whitespace around
582 it, write `*\"\"' in place of just `*'. This is equivalent to just
583 `*' in the shell, but avoids Dired's special handling.
585 If COMMAND produces output, it goes to a separate buffer.
587 This feature does not try to redisplay Dired buffers afterward, as
588 there's no telling what files COMMAND may have changed.
589 Type \\[dired-do-redisplay] to redisplay the marked files.
591 When COMMAND runs, its working directory is the top-level directory
592 of the Dired buffer, so output files usually are created there
593 instead of in a subdir.
595 In a noninteractive call (from Lisp code), you must specify
596 the list of file names explicitly with the FILE-LIST argument, which
597 can be produced by `dired-get-marked-files', for example."
598 ;;Functions dired-run-shell-command and dired-shell-stuff-it do the
599 ;;actual work and can be redefined for customization.
600 (interactive
601 (let ((files (dired-get-marked-files t current-prefix-arg)))
602 (list
603 ;; Want to give feedback whether this file or marked files are used:
604 (dired-read-shell-command (concat "! on "
605 "%s: ")
606 current-prefix-arg
607 files)
608 current-prefix-arg
609 files)))
610 (let* ((on-each (not (string-match dired-star-subst-regexp command)))
611 (no-subst (not (string-match dired-quark-subst-regexp command)))
612 (star (string-match "\\*" command))
613 (qmark (string-match "\\?" command)))
614 ;; Get confirmation for wildcards that may have been meant
615 ;; to control substitution of a file name or the file name list.
616 (if (cond ((not (or on-each no-subst))
617 (error "You can not combine `*' and `?' substitution marks"))
618 ((and star on-each)
619 (y-or-n-p "Confirm--do you mean to use `*' as a wildcard? "))
620 ((and qmark no-subst)
621 (y-or-n-p "Confirm--do you mean to use `?' as a wildcard? "))
622 (t))
623 (if on-each
624 (dired-bunch-files
625 (- 10000 (length command))
626 (function (lambda (&rest files)
627 (dired-run-shell-command
628 (dired-shell-stuff-it command files t arg))))
630 file-list)
631 ;; execute the shell command
632 (dired-run-shell-command
633 (dired-shell-stuff-it command file-list nil arg))))))
635 ;; Might use {,} for bash or csh:
636 (defvar dired-mark-prefix ""
637 "Prepended to marked files in dired shell commands.")
638 (defvar dired-mark-postfix ""
639 "Appended to marked files in dired shell commands.")
640 (defvar dired-mark-separator " "
641 "Separates marked files in dired shell commands.")
643 (defun dired-shell-stuff-it (command file-list on-each &optional _raw-arg)
644 ;; "Make up a shell command line from COMMAND and FILE-LIST.
645 ;; If ON-EACH is t, COMMAND should be applied to each file, else
646 ;; simply concat all files and apply COMMAND to this.
647 ;; FILE-LIST's elements will be quoted for the shell."
648 ;; Might be redefined for smarter things and could then use RAW-ARG
649 ;; (coming from interactive P and currently ignored) to decide what to do.
650 ;; Smart would be a way to access basename or extension of file names.
651 (let ((stuff-it
652 (if (or (string-match dired-star-subst-regexp command)
653 (string-match dired-quark-subst-regexp command))
654 (lambda (x)
655 (let ((retval command))
656 (while (string-match
657 "\\(^\\|[ \t]\\)\\([*?]\\)\\([ \t]\\|$\\)" retval)
658 (setq retval (replace-match x t t retval 2)))
659 retval))
660 (lambda (x) (concat command dired-mark-separator x)))))
661 (if on-each
662 (mapconcat stuff-it (mapcar 'shell-quote-argument file-list) ";")
663 (let ((files (mapconcat 'shell-quote-argument
664 file-list dired-mark-separator)))
665 (if (> (length file-list) 1)
666 (setq files (concat dired-mark-prefix files dired-mark-postfix)))
667 (funcall stuff-it files)))))
669 ;; This is an extra function so that it can be redefined by ange-ftp.
670 ;;;###autoload
671 (defun dired-run-shell-command (command)
672 (let ((handler
673 (find-file-name-handler (directory-file-name default-directory)
674 'shell-command)))
675 (if handler (apply handler 'shell-command (list command))
676 (shell-command command)))
677 ;; Return nil for sake of nconc in dired-bunch-files.
678 nil)
681 (defun dired-check-process (msg program &rest arguments)
682 ; "Display MSG while running PROGRAM, and check for output.
683 ;Remaining arguments are strings passed as command arguments to PROGRAM.
684 ; On error, insert output
685 ; in a log buffer and return the offending ARGUMENTS or PROGRAM.
686 ; Caller can cons up a list of failed args.
687 ;Else returns nil for success."
688 (let (err-buffer err (dir default-directory))
689 (message "%s..." msg)
690 (save-excursion
691 ;; Get a clean buffer for error output:
692 (setq err-buffer (get-buffer-create " *dired-check-process output*"))
693 (set-buffer err-buffer)
694 (erase-buffer)
695 (setq default-directory dir ; caller's default-directory
696 err (not (eq 0 (apply 'process-file program nil t nil arguments))))
697 (if err
698 (progn
699 (dired-log (concat program " " (prin1-to-string arguments) "\n"))
700 (dired-log err-buffer)
701 (or arguments program t))
702 (kill-buffer err-buffer)
703 (message "%s...done" msg)
704 nil))))
706 ;; Commands that delete or redisplay part of the dired buffer.
708 (defun dired-kill-line (&optional arg)
709 "Kill the current line (not the files).
710 With a prefix argument, kill that many lines starting with the current line.
711 \(A negative argument kills backward.)"
712 (interactive "P")
713 (setq arg (prefix-numeric-value arg))
714 (let (buffer-read-only file)
715 (while (/= 0 arg)
716 (setq file (dired-get-filename nil t))
717 (if (not file)
718 (error "Can only kill file lines")
719 (save-excursion (and file
720 (dired-goto-subdir file)
721 (dired-kill-subdir)))
722 (delete-region (line-beginning-position)
723 (progn (forward-line 1) (point)))
724 (if (> arg 0)
725 (setq arg (1- arg))
726 (setq arg (1+ arg))
727 (forward-line -1))))
728 (dired-move-to-filename)))
730 ;;;###autoload
731 (defun dired-do-kill-lines (&optional arg fmt)
732 "Kill all marked lines (not the files).
733 With a prefix argument, kill that many lines starting with the current line.
734 \(A negative argument kills backward.)
735 If you use this command with a prefix argument to kill the line
736 for a file that is a directory, which you have inserted in the
737 Dired buffer as a subdirectory, then it deletes that subdirectory
738 from the buffer as well.
739 To kill an entire subdirectory \(without killing its line in the
740 parent directory), go to its directory header line and use this
741 command with a prefix argument (the value does not matter)."
742 ;; Returns count of killed lines. FMT="" suppresses message.
743 (interactive "P")
744 (if arg
745 (if (dired-get-subdir)
746 (dired-kill-subdir)
747 (dired-kill-line arg))
748 (save-excursion
749 (goto-char (point-min))
750 (let (buffer-read-only
751 (count 0)
752 (regexp (dired-marker-regexp)))
753 (while (and (not (eobp))
754 (re-search-forward regexp nil t))
755 (setq count (1+ count))
756 (delete-region (line-beginning-position)
757 (progn (forward-line 1) (point))))
758 (or (equal "" fmt)
759 (message (or fmt "Killed %d line%s.") count (dired-plural-s count)))
760 count))))
762 ;;;###end dired-cmd.el
764 ;;; 30K
765 ;;;###begin dired-cp.el
767 (defun dired-compress ()
768 ;; Compress or uncompress the current file.
769 ;; Return nil for success, offending filename else.
770 (let* (buffer-read-only
771 (from-file (dired-get-filename))
772 (new-file (dired-compress-file from-file)))
773 (if new-file
774 (let ((start (point)))
775 ;; Remove any preexisting entry for the name NEW-FILE.
776 (condition-case nil
777 (dired-remove-entry new-file)
778 (error nil))
779 (goto-char start)
780 ;; Now replace the current line with an entry for NEW-FILE.
781 (dired-update-file-line new-file) nil)
782 (dired-log (concat "Failed to compress" from-file))
783 from-file)))
785 (defvar dired-compress-file-suffixes
786 '(("\\.gz\\'" "" "gunzip")
787 ("\\.tgz\\'" ".tar" "gunzip")
788 ("\\.Z\\'" "" "uncompress")
789 ;; For .z, try gunzip. It might be an old gzip file,
790 ;; or it might be from compact? pack? (which?) but gunzip handles both.
791 ("\\.z\\'" "" "gunzip")
792 ("\\.dz\\'" "" "dictunzip")
793 ("\\.tbz\\'" ".tar" "bunzip2")
794 ("\\.bz2\\'" "" "bunzip2")
795 ("\\.xz\\'" "" "unxz")
796 ;; This item controls naming for compression.
797 ("\\.tar\\'" ".tgz" nil))
798 "Control changes in file name suffixes for compression and uncompression.
799 Each element specifies one transformation rule, and has the form:
800 (REGEXP NEW-SUFFIX PROGRAM)
801 The rule applies when the old file name matches REGEXP.
802 The new file name is computed by deleting the part that matches REGEXP
803 (as well as anything after that), then adding NEW-SUFFIX in its place.
804 If PROGRAM is non-nil, the rule is an uncompression rule,
805 and uncompression is done by running PROGRAM.
806 Otherwise, the rule is a compression rule, and compression is done with gzip.")
808 ;;;###autoload
809 (defun dired-compress-file (file)
810 ;; Compress or uncompress FILE.
811 ;; Return the name of the compressed or uncompressed file.
812 ;; Return nil if no change in files.
813 (let ((handler (find-file-name-handler file 'dired-compress-file))
814 suffix newname
815 (suffixes dired-compress-file-suffixes))
816 ;; See if any suffix rule matches this file name.
817 (while suffixes
818 (let (case-fold-search)
819 (if (string-match (car (car suffixes)) file)
820 (setq suffix (car suffixes) suffixes nil))
821 (setq suffixes (cdr suffixes))))
822 ;; If so, compute desired new name.
823 (if suffix
824 (setq newname (concat (substring file 0 (match-beginning 0))
825 (nth 1 suffix))))
826 (cond (handler
827 (funcall handler 'dired-compress-file file))
828 ((file-symlink-p file)
829 nil)
830 ((and suffix (nth 2 suffix))
831 ;; We found an uncompression rule.
832 (if (not (dired-check-process (concat "Uncompressing " file)
833 (nth 2 suffix) file))
834 newname))
836 ;;; We don't recognize the file as compressed, so compress it.
837 ;;; Try gzip; if we don't have that, use compress.
838 (condition-case nil
839 (let ((out-name (concat file ".gz")))
840 (and (or (not (file-exists-p out-name))
841 (y-or-n-p
842 (format "File %s already exists. Really compress? "
843 out-name)))
844 (not (dired-check-process (concat "Compressing " file)
845 "gzip" "-f" file))
846 (or (file-exists-p out-name)
847 (setq out-name (concat file ".z")))
848 ;; Rename the compressed file to NEWNAME
849 ;; if it hasn't got that name already.
850 (if (and newname (not (equal newname out-name)))
851 (progn
852 (rename-file out-name newname t)
853 newname)
854 out-name)))
855 (file-error
856 (if (not (dired-check-process (concat "Compressing " file)
857 "compress" "-f" file))
858 ;; Don't use NEWNAME with `compress'.
859 (concat file ".Z"))))))))
861 (defun dired-mark-confirm (op-symbol arg)
862 ;; Request confirmation from the user that the operation described
863 ;; by OP-SYMBOL is to be performed on the marked files.
864 ;; Confirmation consists in a y-or-n question with a file list
865 ;; pop-up unless OP-SYMBOL is a member of `dired-no-confirm'.
866 ;; The files used are determined by ARG (as in dired-get-marked-files).
867 (or (eq dired-no-confirm t)
868 (memq op-symbol dired-no-confirm)
869 ;; Pass t for DISTINGUISH-ONE-MARKED so that a single file which
870 ;; is marked pops up a window. That will help the user see
871 ;; it isn't the current line file.
872 (let ((files (dired-get-marked-files t arg nil t))
873 (string (if (eq op-symbol 'compress) "Compress or uncompress"
874 (capitalize (symbol-name op-symbol)))))
875 (dired-mark-pop-up nil op-symbol files (function y-or-n-p)
876 (concat string " "
877 (dired-mark-prompt arg files) "? ")))))
879 (defun dired-map-over-marks-check (fun arg op-symbol &optional show-progress)
880 ; "Map FUN over marked files (with second ARG like in dired-map-over-marks)
881 ; and display failures.
883 ; FUN takes zero args. It returns non-nil (the offending object, e.g.
884 ; the short form of the filename) for a failure and probably logs a
885 ; detailed error explanation using function `dired-log'.
887 ; OP-SYMBOL is a symbol describing the operation performed (e.g.
888 ; `compress'). It is used with `dired-mark-pop-up' to prompt the user
889 ; (e.g. with `Compress * [2 files]? ') and to display errors (e.g.
890 ; `Failed to compress 1 of 2 files - type W to see why ("foo")')
892 ; SHOW-PROGRESS if non-nil means redisplay dired after each file."
893 (if (dired-mark-confirm op-symbol arg)
894 (let* ((total-list;; all of FUN's return values
895 (dired-map-over-marks (funcall fun) arg show-progress))
896 (total (length total-list))
897 (failures (delq nil total-list))
898 (count (length failures))
899 (string (if (eq op-symbol 'compress) "Compress or uncompress"
900 (capitalize (symbol-name op-symbol)))))
901 (if (not failures)
902 (message "%s: %d file%s."
903 string total (dired-plural-s total))
904 ;; end this bunch of errors:
905 (dired-log-summary
906 (format "Failed to %s %d of %d file%s"
907 (downcase string) count total (dired-plural-s total))
908 failures)))))
910 ;;;###autoload
911 (defun dired-query (sym prompt &rest args)
912 "Format PROMPT with ARGS, query user, and store the result in SYM.
913 The return value is either nil or t.
915 The user may type y or SPC to accept once; n or DEL to skip once;
916 ! to accept this and subsequent queries; or q or ESC to decline
917 this and subsequent queries.
919 If SYM is already bound to a non-nil value, this function may
920 return automatically without querying the user. If SYM is !,
921 return t; if SYM is q or ESC, return nil."
922 (let* ((char (symbol-value sym))
923 (char-choices '(?y ?\s ?n ?\177 ?! ?q ?\e)))
924 (cond ((eq char ?!)
925 t) ; accept, and don't ask again
926 ((memq char '(?q ?\e))
927 nil) ; skip, and don't ask again
928 (t ; no previous answer - ask now
929 (setq prompt
930 (concat (apply 'format prompt args)
931 (if help-form
932 (format " [Type yn!q or %s] "
933 (key-description (vector help-char)))
934 " [Type y, n, q or !] ")))
935 (set sym (setq char (read-char-choice prompt char-choices)))
936 (if (memq char '(?y ?\s ?!)) t)))))
939 ;;;###autoload
940 (defun dired-do-compress (&optional arg)
941 "Compress or uncompress marked (or next ARG) files."
942 (interactive "P")
943 (dired-map-over-marks-check (function dired-compress) arg 'compress t))
945 ;; Commands for Emacs Lisp files - load and byte compile
947 (defun dired-byte-compile ()
948 ;; Return nil for success, offending file name else.
949 (let* ((filename (dired-get-filename))
950 elc-file buffer-read-only failure)
951 (condition-case err
952 (save-excursion (byte-compile-file filename))
953 (error
954 (setq failure err)))
955 (setq elc-file (byte-compile-dest-file filename))
956 (or (file-exists-p elc-file)
957 (setq failure t))
958 (if failure
959 (progn
960 (dired-log "Byte compile error for %s:\n%s\n" filename failure)
961 (dired-make-relative filename))
962 (dired-remove-file elc-file)
963 (forward-line) ; insert .elc after its .el file
964 (dired-add-file elc-file)
965 nil)))
967 ;;;###autoload
968 (defun dired-do-byte-compile (&optional arg)
969 "Byte compile marked (or next ARG) Emacs Lisp files."
970 (interactive "P")
971 (dired-map-over-marks-check (function dired-byte-compile) arg 'byte-compile t))
973 (defun dired-load ()
974 ;; Return nil for success, offending file name else.
975 (let ((file (dired-get-filename)) failure)
976 (condition-case err
977 (load file nil nil t)
978 (error (setq failure err)))
979 (if (not failure)
981 (dired-log "Load error for %s:\n%s\n" file failure)
982 (dired-make-relative file))))
984 ;;;###autoload
985 (defun dired-do-load (&optional arg)
986 "Load the marked (or next ARG) Emacs Lisp files."
987 (interactive "P")
988 (dired-map-over-marks-check (function dired-load) arg 'load t))
990 ;;;###autoload
991 (defun dired-do-redisplay (&optional arg test-for-subdir)
992 "Redisplay all marked (or next ARG) files.
993 If on a subdir line, redisplay that subdirectory. In that case,
994 a prefix arg lets you edit the `ls' switches used for the new listing.
996 Dired remembers switches specified with a prefix arg, so that reverting
997 the buffer will not reset them. However, using `dired-undo' to re-insert
998 or delete subdirectories can bypass this machinery. Hence, you sometimes
999 may have to reset some subdirectory switches after a `dired-undo'.
1000 You can reset all subdirectory switches to the default using
1001 \\<dired-mode-map>\\[dired-reset-subdir-switches].
1002 See Info node `(emacs)Subdir switches' for more details."
1003 ;; Moves point if the next ARG files are redisplayed.
1004 (interactive "P\np")
1005 (if (and test-for-subdir (dired-get-subdir))
1006 (let* ((dir (dired-get-subdir))
1007 (switches (cdr (assoc-string dir dired-switches-alist))))
1008 (dired-insert-subdir
1010 (when arg
1011 (read-string "Switches for listing: "
1012 (or switches
1013 dired-subdir-switches
1014 dired-actual-switches)))))
1015 (message "Redisplaying...")
1016 ;; message much faster than making dired-map-over-marks show progress
1017 (dired-uncache
1018 (if (consp dired-directory) (car dired-directory) dired-directory))
1019 (dired-map-over-marks (let ((fname (dired-get-filename))
1020 ;; Postpone readin hook till we map
1021 ;; over all marked files (Bug#6810).
1022 (dired-after-readin-hook nil))
1023 (message "Redisplaying... %s" fname)
1024 (dired-update-file-line fname))
1025 arg)
1026 (run-hooks 'dired-after-readin-hook)
1027 (dired-move-to-filename)
1028 (message "Redisplaying...done")))
1030 (defun dired-reset-subdir-switches ()
1031 "Set `dired-switches-alist' to nil and revert dired buffer."
1032 (interactive)
1033 (setq dired-switches-alist nil)
1034 (revert-buffer))
1036 (defun dired-update-file-line (file)
1037 ;; Delete the current line, and insert an entry for FILE.
1038 ;; If FILE is nil, then just delete the current line.
1039 ;; Keeps any marks that may be present in column one (doing this
1040 ;; here is faster than with dired-add-entry's optional arg).
1041 ;; Does not update other dired buffers. Use dired-relist-entry for that.
1042 (let* ((opoint (line-beginning-position))
1043 (char (char-after opoint))
1044 (buffer-read-only))
1045 (delete-region opoint (progn (forward-line 1) (point)))
1046 (if file
1047 (progn
1048 (dired-add-entry file nil t)
1049 ;; Replace space by old marker without moving point.
1050 ;; Faster than goto+insdel inside a save-excursion?
1051 (subst-char-in-region opoint (1+ opoint) ?\040 char))))
1052 (dired-move-to-filename))
1054 ;;;###autoload
1055 (defun dired-add-file (filename &optional marker-char)
1056 (dired-fun-in-all-buffers
1057 (file-name-directory filename) (file-name-nondirectory filename)
1058 (function dired-add-entry) filename marker-char))
1060 (defvar dired-omit-mode)
1061 (declare-function dired-omit-regexp "dired-x" ())
1062 (defvar dired-omit-localp)
1064 (defun dired-add-entry (filename &optional marker-char relative)
1065 "Add a new dired entry for FILENAME.
1066 Optionally mark it with MARKER-CHAR (a character, else uses
1067 `dired-marker-char'). Note that this adds the entry `out of order'
1068 if files are sorted by time, etc.
1069 Skips files that match `dired-trivial-filenames'.
1070 Exposes hidden subdirectories if a file is added there.
1072 If `dired-x' is loaded and `dired-omit-mode' is enabled, skips
1073 files matching `dired-omit-regexp'."
1074 (if (or (not (featurep 'dired-x))
1075 (not dired-omit-mode)
1076 ;; Avoid calling ls for files that are going to be omitted anyway.
1077 (let ((omit-re (dired-omit-regexp)))
1078 (or (string= omit-re "")
1079 (not (string-match omit-re
1080 (cond
1081 ((eq 'no-dir dired-omit-localp)
1082 filename)
1083 ((eq t dired-omit-localp)
1084 (dired-make-relative filename))
1086 (dired-make-absolute
1087 filename
1088 (file-name-directory filename)))))))))
1089 ;; Do it!
1090 (progn
1091 (setq filename (directory-file-name filename))
1092 ;; Entry is always for files, even if they happen to also be directories
1093 (let* ((opoint (point))
1094 (cur-dir (dired-current-directory))
1095 (directory (if relative cur-dir (file-name-directory filename)))
1096 reason)
1097 (setq filename
1098 (if relative
1099 (file-relative-name filename directory)
1100 (file-name-nondirectory filename))
1101 reason
1102 (catch 'not-found
1103 (if (string= directory cur-dir)
1104 (progn
1105 (skip-chars-forward "^\r\n")
1106 (if (eq (following-char) ?\r)
1107 (dired-unhide-subdir))
1108 ;; We are already where we should be, except when
1109 ;; point is before the subdir line or its total line.
1110 (let ((p (dired-after-subdir-garbage cur-dir)))
1111 (if (< (point) p)
1112 (goto-char p))))
1113 ;; else try to find correct place to insert
1114 (if (dired-goto-subdir directory)
1115 (progn ;; unhide if necessary
1116 (if (looking-at "\r")
1117 ;; Point is at end of subdir line.
1118 (dired-unhide-subdir))
1119 ;; found - skip subdir and `total' line
1120 ;; and uninteresting files like . and ..
1121 ;; This better not move into the next subdir!
1122 (dired-goto-next-nontrivial-file))
1123 ;; not found
1124 (throw 'not-found "Subdir not found")))
1125 (let (buffer-read-only opoint)
1126 (beginning-of-line)
1127 (setq opoint (point))
1128 ;; Don't expand `.'.
1129 ;; Show just the file name within directory.
1130 (let ((default-directory directory))
1131 (dired-insert-directory
1132 directory
1133 (concat dired-actual-switches " -d")
1134 (list filename)))
1135 (goto-char opoint)
1136 ;; Put in desired marker char.
1137 (when marker-char
1138 (let ((dired-marker-char
1139 (if (integerp marker-char) marker-char
1140 dired-marker-char)))
1141 (dired-mark nil)))
1142 ;; Compensate for a bug in ange-ftp.
1143 ;; It inserts the file's absolute name, rather than
1144 ;; the relative one. That may be hard to fix since it
1145 ;; is probably controlled by something in ftp.
1146 (goto-char opoint)
1147 (let ((inserted-name (dired-get-filename 'verbatim)))
1148 (if (file-name-directory inserted-name)
1149 (let (props)
1150 (end-of-line)
1151 (forward-char (- (length inserted-name)))
1152 (setq props (text-properties-at (point)))
1153 (delete-char (length inserted-name))
1154 (let ((pt (point)))
1155 (insert filename)
1156 (set-text-properties pt (point) props))
1157 (forward-char 1))
1158 (forward-line 1)))
1159 (forward-line -1)
1160 (if dired-after-readin-hook
1161 ;; The subdir-alist is not affected...
1162 (save-excursion ; ...so we can run it right now:
1163 (save-restriction
1164 (beginning-of-line)
1165 (narrow-to-region (point)
1166 (line-beginning-position 2))
1167 (run-hooks 'dired-after-readin-hook))))
1168 (dired-move-to-filename))
1169 ;; return nil if all went well
1170 nil))
1171 (if reason ; don't move away on failure
1172 (goto-char opoint))
1173 (not reason))) ; return t on success, nil else
1174 ;; Don't do it (dired-omit-mode).
1175 ;; Return t for success (perhaps we should return file-exists-p).
1178 (defun dired-after-subdir-garbage (dir)
1179 ;; Return pos of first file line of DIR, skipping header and total
1180 ;; or wildcard lines.
1181 ;; Important: never moves into the next subdir.
1182 ;; DIR is assumed to be unhidden.
1183 (save-excursion
1184 (or (dired-goto-subdir dir) (error "This cannot happen"))
1185 (forward-line 1)
1186 (while (and (not (eolp)) ; don't cross subdir boundary
1187 (not (dired-move-to-filename)))
1188 (forward-line 1))
1189 (point)))
1191 ;;;###autoload
1192 (defun dired-remove-file (file)
1193 (dired-fun-in-all-buffers
1194 (file-name-directory file) (file-name-nondirectory file)
1195 (function dired-remove-entry) file))
1197 (defun dired-remove-entry (file)
1198 (save-excursion
1199 (and (dired-goto-file file)
1200 (let (buffer-read-only)
1201 (delete-region (progn (beginning-of-line) (point))
1202 (line-beginning-position 2))))))
1204 ;;;###autoload
1205 (defun dired-relist-file (file)
1206 "Create or update the line for FILE in all Dired buffers it would belong in."
1207 (dired-fun-in-all-buffers (file-name-directory file)
1208 (file-name-nondirectory file)
1209 (function dired-relist-entry) file))
1211 (defun dired-relist-entry (file)
1212 ;; Relist the line for FILE, or just add it if it did not exist.
1213 ;; FILE must be an absolute file name.
1214 (let (buffer-read-only marker)
1215 ;; If cursor is already on FILE's line delete-region will cause
1216 ;; save-excursion to fail because of floating makers,
1217 ;; moving point to beginning of line. Sigh.
1218 (save-excursion
1219 (and (dired-goto-file file)
1220 (delete-region (progn (beginning-of-line)
1221 (setq marker (following-char))
1222 (point))
1223 (line-beginning-position 2)))
1224 (setq file (directory-file-name file))
1225 (dired-add-entry file (if (eq ?\040 marker) nil marker)))))
1227 ;;; Copy, move/rename, making hard and symbolic links
1229 (defcustom dired-backup-overwrite nil
1230 "Non-nil if Dired should ask about making backups before overwriting files.
1231 Special value `always' suppresses confirmation."
1232 :type '(choice (const :tag "off" nil)
1233 (const :tag "suppress" always)
1234 (other :tag "ask" t))
1235 :group 'dired)
1237 ;; This is a fluid var used in dired-handle-overwrite. It should be
1238 ;; let-bound whenever dired-copy-file etc are called. See
1239 ;; dired-create-files for an example.
1240 (defvar dired-overwrite-confirmed)
1242 (defun dired-handle-overwrite (to)
1243 ;; Save old version of file TO that is to be overwritten.
1244 ;; `dired-overwrite-confirmed' and `overwrite-backup-query' are fluid vars
1245 ;; from dired-create-files.
1246 (let (backup)
1247 (when (and dired-backup-overwrite
1248 dired-overwrite-confirmed
1249 (setq backup (car (find-backup-file-name to)))
1250 (or (eq 'always dired-backup-overwrite)
1251 (dired-query 'overwrite-backup-query
1252 "Make backup for existing file `%s'? "
1253 to)))
1254 (rename-file to backup 0) ; confirm overwrite of old backup
1255 (dired-relist-entry backup))))
1257 ;;;###autoload
1258 (defun dired-copy-file (from to ok-flag)
1259 (dired-handle-overwrite to)
1260 (dired-copy-file-recursive from to ok-flag dired-copy-preserve-time t
1261 dired-recursive-copies))
1263 (declare-function make-symbolic-link "fileio.c")
1265 (defun dired-copy-file-recursive (from to ok-flag &optional
1266 preserve-time top recursive)
1267 (when (file-subdir-of-p to from)
1268 (error "Cannot copy `%s' into its subdirectory `%s'" from to))
1269 (let ((attrs (file-attributes from)))
1270 (if (and recursive
1271 (eq t (car attrs))
1272 (or (eq recursive 'always)
1273 (yes-or-no-p (format "Recursive copies of %s? " from))))
1274 ;; This is a directory.
1275 (copy-directory from to preserve-time)
1276 ;; Not a directory.
1277 (or top (dired-handle-overwrite to))
1278 (condition-case err
1279 (if (stringp (car attrs))
1280 ;; It is a symlink
1281 (make-symbolic-link (car attrs) to ok-flag)
1282 (copy-file from to ok-flag preserve-time))
1283 (file-date-error
1284 (push (dired-make-relative from)
1285 dired-create-files-failures)
1286 (dired-log "Can't set date on %s:\n%s\n" from err))))))
1288 ;;;###autoload
1289 (defun dired-rename-file (file newname ok-if-already-exists)
1290 (dired-handle-overwrite newname)
1291 (rename-file file newname ok-if-already-exists) ; error is caught in -create-files
1292 ;; Silently rename the visited file of any buffer visiting this file.
1293 (and (get-file-buffer file)
1294 (with-current-buffer (get-file-buffer file)
1295 (set-visited-file-name newname nil t)))
1296 (dired-remove-file file)
1297 ;; See if it's an inserted subdir, and rename that, too.
1298 (dired-rename-subdir file newname))
1300 (defun dired-rename-subdir (from-dir to-dir)
1301 (setq from-dir (file-name-as-directory from-dir)
1302 to-dir (file-name-as-directory to-dir))
1303 (dired-fun-in-all-buffers from-dir nil
1304 (function dired-rename-subdir-1) from-dir to-dir)
1305 ;; Update visited file name of all affected buffers
1306 (let ((expanded-from-dir (expand-file-name from-dir))
1307 (blist (buffer-list)))
1308 (while blist
1309 (with-current-buffer (car blist)
1310 (if (and buffer-file-name
1311 (dired-in-this-tree buffer-file-name expanded-from-dir))
1312 (let ((modflag (buffer-modified-p))
1313 (to-file (dired-replace-in-string
1314 (concat "^" (regexp-quote from-dir))
1315 to-dir
1316 buffer-file-name)))
1317 (set-visited-file-name to-file)
1318 (set-buffer-modified-p modflag))))
1319 (setq blist (cdr blist)))))
1321 (defun dired-rename-subdir-1 (dir to)
1322 ;; Rename DIR to TO in headerlines and dired-subdir-alist, if DIR or
1323 ;; one of its subdirectories is expanded in this buffer.
1324 (let ((expanded-dir (expand-file-name dir))
1325 (alist dired-subdir-alist)
1326 (elt nil))
1327 (while alist
1328 (setq elt (car alist)
1329 alist (cdr alist))
1330 (if (dired-in-this-tree (car elt) expanded-dir)
1331 ;; ELT's subdir is affected by the rename
1332 (dired-rename-subdir-2 elt dir to)))
1333 (if (equal dir default-directory)
1334 ;; if top level directory was renamed, lots of things have to be
1335 ;; updated:
1336 (progn
1337 (dired-unadvertise dir) ; we no longer dired DIR...
1338 (setq default-directory to
1339 dired-directory (expand-file-name;; this is correct
1340 ;; with and without wildcards
1341 (file-name-nondirectory dired-directory)
1342 to))
1343 (let ((new-name (file-name-nondirectory
1344 (directory-file-name dired-directory))))
1345 ;; try to rename buffer, but just leave old name if new
1346 ;; name would already exist (don't try appending "<%d>")
1347 (or (get-buffer new-name)
1348 (rename-buffer new-name)))
1349 ;; ... we dired TO now:
1350 (dired-advertise)))))
1352 (defun dired-rename-subdir-2 (elt dir to)
1353 ;; Update the headerline and dired-subdir-alist element, as well as
1354 ;; dired-switches-alist element, of directory described by
1355 ;; alist-element ELT to reflect the moving of DIR to TO. Thus, ELT
1356 ;; describes either DIR itself or a subdir of DIR.
1357 (save-excursion
1358 (let ((regexp (regexp-quote (directory-file-name dir)))
1359 (newtext (directory-file-name to))
1360 buffer-read-only)
1361 (goto-char (dired-get-subdir-min elt))
1362 ;; Update subdir headerline in buffer
1363 (if (not (looking-at dired-subdir-regexp))
1364 (error "%s not found where expected - dired-subdir-alist broken?"
1365 dir)
1366 (goto-char (match-beginning 1))
1367 (if (re-search-forward regexp (match-end 1) t)
1368 (replace-match newtext t t)
1369 (error "Expected to find `%s' in headerline of %s" dir (car elt))))
1370 ;; Update buffer-local dired-subdir-alist and dired-switches-alist
1371 (let ((cons (assoc-string (car elt) dired-switches-alist))
1372 (cur-dir (dired-normalize-subdir
1373 (dired-replace-in-string regexp newtext (car elt)))))
1374 (setcar elt cur-dir)
1375 (when cons (setcar cons cur-dir))))))
1377 ;; Bound in dired-create-files
1378 (defvar overwrite-query)
1379 (defvar overwrite-backup-query)
1381 ;; The basic function for half a dozen variations on cp/mv/ln/ln -s.
1382 (defun dired-create-files (file-creator operation fn-list name-constructor
1383 &optional marker-char)
1384 "Create one or more new files from a list of existing files FN-LIST.
1385 This function also handles querying the user, updating Dired
1386 buffers, and displaying a success or failure message.
1388 FILE-CREATOR should be a function. It is called once for each
1389 file in FN-LIST, and must create a new file, querying the user
1390 and updating Dired buffers as necessary. It should accept three
1391 arguments: the old file name, the new name, and an argument
1392 OK-IF-ALREADY-EXISTS with the same meaning as in `copy-file'.
1394 OPERATION should be a capitalized string describing the operation
1395 performed (e.g. `Copy'). It is used for error logging.
1397 FN-LIST is the list of files to copy (full absolute file names).
1399 NAME-CONSTRUCTOR should be a function accepting a single
1400 argument, the name of an old file, and returning either the
1401 corresponding new file name or nil to skip.
1403 Optional MARKER-CHAR is a character with which to mark every
1404 newfile's entry, or t to use the current marker character if the
1405 old file was marked."
1406 (let (dired-create-files-failures failures
1407 skipped (success-count 0) (total (length fn-list)))
1408 (let (to overwrite-query
1409 overwrite-backup-query) ; for dired-handle-overwrite
1410 (dolist (from fn-list)
1411 (setq to (funcall name-constructor from))
1412 (if (equal to from)
1413 (progn
1414 (setq to nil)
1415 (dired-log "Cannot %s to same file: %s\n"
1416 (downcase operation) from)))
1417 (if (not to)
1418 (setq skipped (cons (dired-make-relative from) skipped))
1419 (let* ((overwrite (file-exists-p to))
1420 (dired-overwrite-confirmed ; for dired-handle-overwrite
1421 (and overwrite
1422 (let ((help-form '(format "\
1423 Type SPC or `y' to overwrite file `%s',
1424 DEL or `n' to skip to next,
1425 ESC or `q' to not overwrite any of the remaining files,
1426 `!' to overwrite all remaining files with no more questions." to)))
1427 (dired-query 'overwrite-query
1428 "Overwrite `%s'?" to))))
1429 ;; must determine if FROM is marked before file-creator
1430 ;; gets a chance to delete it (in case of a move).
1431 (actual-marker-char
1432 (cond ((integerp marker-char) marker-char)
1433 (marker-char (dired-file-marker from)) ; slow
1434 (t nil))))
1435 ;; Handle the `dired-copy-file' file-creator specially
1436 ;; When copying a directory to another directory or
1437 ;; possibly to itself or one of its subdirectories.
1438 ;; e.g "~/foo/" => "~/test/"
1439 ;; or "~/foo/" =>"~/foo/"
1440 ;; or "~/foo/ => ~/foo/bar/")
1441 ;; In this case the 'name-constructor' have set the destination
1442 ;; TO to "~/test/foo" because the old emacs23 behavior
1443 ;; of `copy-directory' was to not create the subdirectory
1444 ;; and instead copy the contents.
1445 ;; With the new behavior of `copy-directory'
1446 ;; (similar to the `cp' shell command) we don't
1447 ;; need such a construction of the target directory,
1448 ;; so modify the destination TO to "~/test/" instead of "~/test/foo/".
1449 (let ((destname (file-name-directory to)))
1450 (when (and (file-directory-p from)
1451 (file-directory-p to)
1452 (eq file-creator 'dired-copy-file))
1453 (setq to destname))
1454 ;; If DESTNAME and FROM are the same directory or
1455 ;; If DESTNAME is a subdirectory of FROM, return error.
1456 (and (file-subdir-of-p destname from)
1457 (error "Cannot copy `%s' into its subdirectory `%s'"
1458 from to)))
1459 (condition-case err
1460 (progn
1461 (funcall file-creator from to dired-overwrite-confirmed)
1462 (if overwrite
1463 ;; If we get here, file-creator hasn't been aborted
1464 ;; and the old entry (if any) has to be deleted
1465 ;; before adding the new entry.
1466 (dired-remove-file to))
1467 (setq success-count (1+ success-count))
1468 (message "%s: %d of %d" operation success-count total)
1469 (dired-add-file to actual-marker-char))
1470 (file-error ; FILE-CREATOR aborted
1471 (progn
1472 (push (dired-make-relative from)
1473 failures)
1474 (dired-log "%s `%s' to `%s' failed:\n%s\n"
1475 operation from to err))))))))
1476 (cond
1477 (dired-create-files-failures
1478 (setq failures (nconc failures dired-create-files-failures))
1479 (dired-log-summary
1480 (format "%s failed for %d file%s in %d requests"
1481 operation (length failures)
1482 (dired-plural-s (length failures))
1483 total)
1484 failures))
1485 (failures
1486 (dired-log-summary
1487 (format "%s failed for %d of %d file%s"
1488 operation (length failures)
1489 total (dired-plural-s total))
1490 failures))
1491 (skipped
1492 (dired-log-summary
1493 (format "%s: %d of %d file%s skipped"
1494 operation (length skipped) total
1495 (dired-plural-s total))
1496 skipped))
1498 (message "%s: %s file%s"
1499 operation success-count (dired-plural-s success-count)))))
1500 (dired-move-to-filename))
1502 (defun dired-do-create-files (op-symbol file-creator operation arg
1503 &optional marker-char op1
1504 how-to)
1505 "Create a new file for each marked file.
1506 Prompts user for target, which is a directory in which to create
1507 the new files. Target may also be a plain file if only one marked
1508 file exists. The way the default for the target directory is
1509 computed depends on the value of `dired-dwim-target-directory'.
1510 OP-SYMBOL is the symbol for the operation. Function `dired-mark-pop-up'
1511 will determine whether pop-ups are appropriate for this OP-SYMBOL.
1512 FILE-CREATOR and OPERATION as in `dired-create-files'.
1513 ARG as in `dired-get-marked-files'.
1514 Optional arg MARKER-CHAR as in `dired-create-files'.
1515 Optional arg OP1 is an alternate form for OPERATION if there is
1516 only one file.
1517 Optional arg HOW-TO determines how to treat the target.
1518 If HOW-TO is nil, use `file-directory-p' to determine if the
1519 target is a directory. If so, the marked file(s) are created
1520 inside that directory. Otherwise, the target is a plain file;
1521 an error is raised unless there is exactly one marked file.
1522 If HOW-TO is t, target is always treated as a plain file.
1523 Otherwise, HOW-TO should be a function of one argument, TARGET.
1524 If its return value is nil, TARGET is regarded as a plain file.
1525 If it return value is a list, TARGET is a generalized
1526 directory (e.g. some sort of archive). The first element of
1527 this list must be a function with at least four arguments:
1528 operation - as OPERATION above.
1529 rfn-list - list of the relative names for the marked files.
1530 fn-list - list of the absolute names for the marked files.
1531 target - the name of the target itself.
1532 The rest of into-dir are optional arguments.
1533 For any other return value, TARGET is treated as a directory."
1534 (or op1 (setq op1 operation))
1535 (let* ((fn-list (dired-get-marked-files nil arg))
1536 (rfn-list (mapcar (function dired-make-relative) fn-list))
1537 (dired-one-file ; fluid variable inside dired-create-files
1538 (and (consp fn-list) (null (cdr fn-list)) (car fn-list)))
1539 (target-dir (dired-dwim-target-directory))
1540 (default (and dired-one-file
1541 (expand-file-name (file-name-nondirectory (car fn-list))
1542 target-dir)))
1543 (defaults (dired-dwim-target-defaults fn-list target-dir))
1544 (target (expand-file-name ; fluid variable inside dired-create-files
1545 (minibuffer-with-setup-hook
1546 (lambda ()
1547 (set (make-local-variable 'minibuffer-default-add-function) nil)
1548 (setq minibuffer-default defaults))
1549 (dired-mark-read-file-name
1550 (concat (if dired-one-file op1 operation) " %s to: ")
1551 target-dir op-symbol arg rfn-list default))))
1552 (into-dir (cond ((null how-to)
1553 ;; Allow DOS/Windows users to change the letter
1554 ;; case of a directory. If we don't test these
1555 ;; conditions up front, file-directory-p below
1556 ;; will return t because the filesystem is
1557 ;; case-insensitive, and Emacs will try to move
1558 ;; foo -> foo/foo, which fails.
1559 (if (and (memq system-type '(ms-dos windows-nt cygwin))
1560 (eq op-symbol 'move)
1561 dired-one-file
1562 (string= (downcase
1563 (expand-file-name (car fn-list)))
1564 (downcase
1565 (expand-file-name target)))
1566 (not (string=
1567 (file-name-nondirectory (car fn-list))
1568 (file-name-nondirectory target))))
1570 (file-directory-p target)))
1571 ((eq how-to t) nil)
1572 (t (funcall how-to target)))))
1573 (if (and (consp into-dir) (functionp (car into-dir)))
1574 (apply (car into-dir) operation rfn-list fn-list target (cdr into-dir))
1575 (if (not (or dired-one-file into-dir))
1576 (error "Marked %s: target must be a directory: %s" operation target))
1577 ;; rename-file bombs when moving directories unless we do this:
1578 (or into-dir (setq target (directory-file-name target)))
1579 (dired-create-files
1580 file-creator operation fn-list
1581 (if into-dir ; target is a directory
1582 ;; This function uses fluid variable target when called
1583 ;; inside dired-create-files:
1584 (function
1585 (lambda (from)
1586 (expand-file-name (file-name-nondirectory from) target)))
1587 (function (lambda (_from) target)))
1588 marker-char))))
1590 ;; Read arguments for a marked-files command that wants a file name,
1591 ;; perhaps popping up the list of marked files.
1592 ;; ARG is the prefix arg and indicates whether the files came from
1593 ;; marks (ARG=nil) or a repeat factor (integerp ARG).
1594 ;; If the current file was used, the list has but one element and ARG
1595 ;; does not matter. (It is non-nil, non-integer in that case, namely '(4)).
1596 ;; DEFAULT is the default value to return if the user just hits RET;
1597 ;; if it is omitted or nil, then the name of the directory is used.
1599 (defun dired-mark-read-file-name (prompt dir op-symbol arg files
1600 &optional default)
1601 (dired-mark-pop-up
1602 nil op-symbol files
1603 (function read-file-name)
1604 (format prompt (dired-mark-prompt arg files)) dir default))
1606 (defun dired-dwim-target-directory ()
1607 ;; Try to guess which target directory the user may want.
1608 ;; If there is a dired buffer displayed in one of the next windows,
1609 ;; use its current subdir, else use current subdir of this dired buffer.
1610 (let ((this-dir (and (eq major-mode 'dired-mode)
1611 (dired-current-directory))))
1612 ;; non-dired buffer may want to profit from this function, e.g. vm-uudecode
1613 (if dired-dwim-target
1614 (let* ((other-win (get-window-with-predicate
1615 (lambda (window)
1616 (with-current-buffer (window-buffer window)
1617 (eq major-mode 'dired-mode)))))
1618 (other-dir (and other-win
1619 (with-current-buffer (window-buffer other-win)
1620 (and (eq major-mode 'dired-mode)
1621 (dired-current-directory))))))
1622 (or other-dir this-dir))
1623 this-dir)))
1625 (defun dired-dwim-target-defaults (fn-list target-dir)
1626 ;; Return a list of default values for file-reading functions in Dired.
1627 ;; This list may contain directories from Dired buffers in other windows.
1628 ;; `fn-list' is a list of file names used to build a list of defaults.
1629 ;; When nil or more than one element, a list of defaults will
1630 ;; contain only directory names. `target-dir' is a directory name
1631 ;; to exclude from the returned list, for the case when this
1632 ;; directory name is already presented in initial input.
1633 ;; For Dired operations that support `dired-dwim-target',
1634 ;; the argument `target-dir' should have the value returned
1635 ;; from `dired-dwim-target-directory'.
1636 (let ((dired-one-file
1637 (and (consp fn-list) (null (cdr fn-list)) (car fn-list)))
1638 (current-dir (and (eq major-mode 'dired-mode)
1639 (dired-current-directory)))
1640 dired-dirs)
1641 ;; Get a list of directories of visible buffers in dired-mode.
1642 (walk-windows (lambda (w)
1643 (with-current-buffer (window-buffer w)
1644 (and (eq major-mode 'dired-mode)
1645 (push (dired-current-directory) dired-dirs)))))
1646 ;; Force the current dir to be the first in the list.
1647 (setq dired-dirs
1648 (delete-dups (delq nil (cons current-dir (nreverse dired-dirs)))))
1649 ;; Remove the target dir (if specified) or the current dir from
1650 ;; default values, because it should be already in initial input.
1651 (setq dired-dirs (delete (or target-dir current-dir) dired-dirs))
1652 ;; Return a list of default values.
1653 (if dired-one-file
1654 ;; For one file operation, provide a list that contains
1655 ;; other directories, other directories with the appended filename
1656 ;; and the current directory with the appended filename, e.g.
1657 ;; 1. /TARGET-DIR/
1658 ;; 2. /TARGET-DIR/FILENAME
1659 ;; 3. /CURRENT-DIR/FILENAME
1660 (append dired-dirs
1661 (mapcar (lambda (dir)
1662 (expand-file-name
1663 (file-name-nondirectory (car fn-list)) dir))
1664 (reverse dired-dirs))
1665 (list (expand-file-name
1666 (file-name-nondirectory (car fn-list))
1667 (or target-dir current-dir))))
1668 ;; For multi-file operation, return only a list of other directories.
1669 dired-dirs)))
1672 ;;;###autoload
1673 (defun dired-create-directory (directory)
1674 "Create a directory called DIRECTORY.
1675 If DIRECTORY already exists, signal an error."
1676 (interactive
1677 (list (read-file-name "Create directory: " (dired-current-directory))))
1678 (let* ((expanded (directory-file-name (expand-file-name directory)))
1679 (try expanded) new)
1680 (if (file-exists-p expanded)
1681 (error "Cannot create directory %s: file exists" expanded))
1682 ;; Find the topmost nonexistent parent dir (variable `new')
1683 (while (and try (not (file-exists-p try)) (not (equal new try)))
1684 (setq new try
1685 try (directory-file-name (file-name-directory try))))
1686 (make-directory expanded t)
1687 (when new
1688 (dired-add-file new)
1689 (dired-move-to-filename))))
1691 (defun dired-into-dir-with-symlinks (target)
1692 (and (file-directory-p target)
1693 (not (file-symlink-p target))))
1694 ;; This may not always be what you want, especially if target is your
1695 ;; home directory and it happens to be a symbolic link, as is often the
1696 ;; case with NFS and automounters. Or if you want to make symlinks
1697 ;; into directories that themselves are only symlinks, also quite
1698 ;; common.
1700 ;; So we don't use this function as value for HOW-TO in
1701 ;; dired-do-symlink, which has the minor disadvantage of
1702 ;; making links *into* a symlinked-dir, when you really wanted to
1703 ;; *overwrite* that symlink. In that (rare, I guess) case, you'll
1704 ;; just have to remove that symlink by hand before making your marked
1705 ;; symlinks.
1707 (defvar dired-copy-how-to-fn nil
1708 "Either nil or a function used by `dired-do-copy' to determine target.
1709 See HOW-TO argument for `dired-do-create-files'.")
1711 ;;;###autoload
1712 (defun dired-do-copy (&optional arg)
1713 "Copy all marked (or next ARG) files, or copy the current file.
1714 This normally preserves the last-modified date when copying.
1715 When operating on just the current file, you specify the new name.
1716 When operating on multiple or marked files, you specify a directory,
1717 and new copies of these files are made in that directory
1718 with the same names that the files currently have. The default
1719 suggested for the target directory depends on the value of
1720 `dired-dwim-target', which see.
1722 This command copies symbolic links by creating new ones,
1723 like `cp -d'."
1724 (interactive "P")
1725 (let ((dired-recursive-copies dired-recursive-copies))
1726 (dired-do-create-files 'copy (function dired-copy-file)
1727 "Copy"
1728 arg dired-keep-marker-copy
1729 nil dired-copy-how-to-fn)))
1731 ;;;###autoload
1732 (defun dired-do-symlink (&optional arg)
1733 "Make symbolic links to current file or all marked (or next ARG) files.
1734 When operating on just the current file, you specify the new name.
1735 When operating on multiple or marked files, you specify a directory
1736 and new symbolic links are made in that directory
1737 with the same names that the files currently have. The default
1738 suggested for the target directory depends on the value of
1739 `dired-dwim-target', which see.
1741 For relative symlinks, use \\[dired-do-relsymlink]."
1742 (interactive "P")
1743 (dired-do-create-files 'symlink (function make-symbolic-link)
1744 "Symlink" arg dired-keep-marker-symlink))
1746 ;;;###autoload
1747 (defun dired-do-hardlink (&optional arg)
1748 "Add names (hard links) current file or all marked (or next ARG) files.
1749 When operating on just the current file, you specify the new name.
1750 When operating on multiple or marked files, you specify a directory
1751 and new hard links are made in that directory
1752 with the same names that the files currently have. The default
1753 suggested for the target directory depends on the value of
1754 `dired-dwim-target', which see."
1755 (interactive "P")
1756 (dired-do-create-files 'hardlink (function dired-hardlink)
1757 "Hardlink" arg dired-keep-marker-hardlink))
1759 (defun dired-hardlink (file newname &optional ok-if-already-exists)
1760 (dired-handle-overwrite newname)
1761 ;; error is caught in -create-files
1762 (add-name-to-file file newname ok-if-already-exists)
1763 ;; Update the link count
1764 (dired-relist-file file))
1766 ;;;###autoload
1767 (defun dired-do-rename (&optional arg)
1768 "Rename current file or all marked (or next ARG) files.
1769 When renaming just the current file, you specify the new name.
1770 When renaming multiple or marked files, you specify a directory.
1771 This command also renames any buffers that are visiting the files.
1772 The default suggested for the target directory depends on the value
1773 of `dired-dwim-target', which see."
1774 (interactive "P")
1775 (dired-do-create-files 'move (function dired-rename-file)
1776 "Move" arg dired-keep-marker-rename "Rename"))
1777 ;;;###end dired-cp.el
1779 ;;; 5K
1780 ;;;###begin dired-re.el
1781 (defvar rename-regexp-query)
1783 (defun dired-do-create-files-regexp
1784 (file-creator operation arg regexp newname &optional whole-name marker-char)
1785 ;; Create a new file for each marked file using regexps.
1786 ;; FILE-CREATOR and OPERATION as in dired-create-files.
1787 ;; ARG as in dired-get-marked-files.
1788 ;; Matches each marked file against REGEXP and constructs the new
1789 ;; filename from NEWNAME (like in function replace-match).
1790 ;; Optional arg WHOLE-NAME means match/replace the whole file name
1791 ;; instead of only the non-directory part of the file.
1792 ;; Optional arg MARKER-CHAR as in dired-create-files.
1793 (let* ((fn-list (dired-get-marked-files nil arg))
1794 (operation-prompt (concat operation " `%s' to `%s'?"))
1795 (rename-regexp-help-form (format "\
1796 Type SPC or `y' to %s one match, DEL or `n' to skip to next,
1797 `!' to %s all remaining matches with no more questions."
1798 (downcase operation)
1799 (downcase operation)))
1800 (regexp-name-constructor
1801 ;; Function to construct new filename using REGEXP and NEWNAME:
1802 (if whole-name ; easy (but rare) case
1803 (function
1804 (lambda (from)
1805 (let ((to (dired-string-replace-match regexp from newname))
1806 ;; must bind help-form directly around call to
1807 ;; dired-query
1808 (help-form rename-regexp-help-form))
1809 (if to
1810 (and (dired-query 'rename-regexp-query
1811 operation-prompt
1812 from
1815 (dired-log "%s: %s did not match regexp %s\n"
1816 operation from regexp)))))
1817 ;; not whole-name, replace non-directory part only
1818 (function
1819 (lambda (from)
1820 (let* ((new (dired-string-replace-match
1821 regexp (file-name-nondirectory from) newname))
1822 (to (and new ; nil means there was no match
1823 (expand-file-name new
1824 (file-name-directory from))))
1825 (help-form rename-regexp-help-form))
1826 (if to
1827 (and (dired-query 'rename-regexp-query
1828 operation-prompt
1829 (dired-make-relative from)
1830 (dired-make-relative to))
1832 (dired-log "%s: %s did not match regexp %s\n"
1833 operation (file-name-nondirectory from) regexp)))))))
1834 rename-regexp-query)
1835 (dired-create-files
1836 file-creator operation fn-list regexp-name-constructor marker-char)))
1838 (defun dired-mark-read-regexp (operation)
1839 ;; Prompt user about performing OPERATION.
1840 ;; Read and return list of: regexp newname arg whole-name.
1841 (let* ((whole-name
1842 (equal 0 (prefix-numeric-value current-prefix-arg)))
1843 (arg
1844 (if whole-name nil current-prefix-arg))
1845 (regexp
1846 (dired-read-regexp
1847 (concat (if whole-name "Abs. " "") operation " from (regexp): ")))
1848 (newname
1849 (read-string
1850 (concat (if whole-name "Abs. " "") operation " " regexp " to: "))))
1851 (list regexp newname arg whole-name)))
1853 ;;;###autoload
1854 (defun dired-do-rename-regexp (regexp newname &optional arg whole-name)
1855 "Rename selected files whose names match REGEXP to NEWNAME.
1857 With non-zero prefix argument ARG, the command operates on the next ARG
1858 files. Otherwise, it operates on all the marked files, or the current
1859 file if none are marked.
1861 As each match is found, the user must type a character saying
1862 what to do with it. For directions, type \\[help-command] at that time.
1863 NEWNAME may contain \\=\\<n> or \\& as in `query-replace-regexp'.
1864 REGEXP defaults to the last regexp used.
1866 With a zero prefix arg, renaming by regexp affects the absolute file name.
1867 Normally, only the non-directory part of the file name is used and changed."
1868 (interactive (dired-mark-read-regexp "Rename"))
1869 (dired-do-create-files-regexp
1870 (function dired-rename-file)
1871 "Rename" arg regexp newname whole-name dired-keep-marker-rename))
1873 ;;;###autoload
1874 (defun dired-do-copy-regexp (regexp newname &optional arg whole-name)
1875 "Copy selected files whose names match REGEXP to NEWNAME.
1876 See function `dired-do-rename-regexp' for more info."
1877 (interactive (dired-mark-read-regexp "Copy"))
1878 (let ((dired-recursive-copies nil)) ; No recursive copies.
1879 (dired-do-create-files-regexp
1880 (function dired-copy-file)
1881 (if dired-copy-preserve-time "Copy [-p]" "Copy")
1882 arg regexp newname whole-name dired-keep-marker-copy)))
1884 ;;;###autoload
1885 (defun dired-do-hardlink-regexp (regexp newname &optional arg whole-name)
1886 "Hardlink selected files whose names match REGEXP to NEWNAME.
1887 See function `dired-do-rename-regexp' for more info."
1888 (interactive (dired-mark-read-regexp "HardLink"))
1889 (dired-do-create-files-regexp
1890 (function add-name-to-file)
1891 "HardLink" arg regexp newname whole-name dired-keep-marker-hardlink))
1893 ;;;###autoload
1894 (defun dired-do-symlink-regexp (regexp newname &optional arg whole-name)
1895 "Symlink selected files whose names match REGEXP to NEWNAME.
1896 See function `dired-do-rename-regexp' for more info."
1897 (interactive (dired-mark-read-regexp "SymLink"))
1898 (dired-do-create-files-regexp
1899 (function make-symbolic-link)
1900 "SymLink" arg regexp newname whole-name dired-keep-marker-symlink))
1902 (defvar rename-non-directory-query)
1904 (defun dired-create-files-non-directory
1905 (file-creator basename-constructor operation arg)
1906 ;; Perform FILE-CREATOR on the non-directory part of marked files
1907 ;; using function BASENAME-CONSTRUCTOR, with query for each file.
1908 ;; OPERATION like in dired-create-files, ARG as in dired-get-marked-files.
1909 (let (rename-non-directory-query)
1910 (dired-create-files
1911 file-creator
1912 operation
1913 (dired-get-marked-files nil arg)
1914 (function
1915 (lambda (from)
1916 (let ((to (concat (file-name-directory from)
1917 (funcall basename-constructor
1918 (file-name-nondirectory from)))))
1919 (and (let ((help-form (format "\
1920 Type SPC or `y' to %s one file, DEL or `n' to skip to next,
1921 `!' to %s all remaining matches with no more questions."
1922 (downcase operation)
1923 (downcase operation))))
1924 (dired-query 'rename-non-directory-query
1925 (concat operation " `%s' to `%s'")
1926 (dired-make-relative from)
1927 (dired-make-relative to)))
1928 to))))
1929 dired-keep-marker-rename)))
1931 (defun dired-rename-non-directory (basename-constructor operation arg)
1932 (dired-create-files-non-directory
1933 (function dired-rename-file)
1934 basename-constructor operation arg))
1936 ;;;###autoload
1937 (defun dired-upcase (&optional arg)
1938 "Rename all marked (or next ARG) files to upper case."
1939 (interactive "P")
1940 (dired-rename-non-directory (function upcase) "Rename upcase" arg))
1942 ;;;###autoload
1943 (defun dired-downcase (&optional arg)
1944 "Rename all marked (or next ARG) files to lower case."
1945 (interactive "P")
1946 (dired-rename-non-directory (function downcase) "Rename downcase" arg))
1948 ;;;###end dired-re.el
1950 ;;; 13K
1951 ;;;###begin dired-ins.el
1953 ;;;###autoload
1954 (defun dired-maybe-insert-subdir (dirname &optional
1955 switches no-error-if-not-dir-p)
1956 "Insert this subdirectory into the same dired buffer.
1957 If it is already present, just move to it (type \\[dired-do-redisplay] to refresh),
1958 else inserts it at its natural place (as `ls -lR' would have done).
1959 With a prefix arg, you may edit the ls switches used for this listing.
1960 You can add `R' to the switches to expand the whole tree starting at
1961 this subdirectory.
1962 This function takes some pains to conform to `ls -lR' output.
1964 Dired remembers switches specified with a prefix arg, so that reverting
1965 the buffer will not reset them. However, using `dired-undo' to re-insert
1966 or delete subdirectories can bypass this machinery. Hence, you sometimes
1967 may have to reset some subdirectory switches after a `dired-undo'.
1968 You can reset all subdirectory switches to the default using
1969 \\<dired-mode-map>\\[dired-reset-subdir-switches].
1970 See Info node `(emacs)Subdir switches' for more details."
1971 (interactive
1972 (list (dired-get-filename)
1973 (if current-prefix-arg
1974 (read-string "Switches for listing: "
1975 (or dired-subdir-switches dired-actual-switches)))))
1976 (let ((opoint (point)))
1977 ;; We don't need a marker for opoint as the subdir is always
1978 ;; inserted *after* opoint.
1979 (setq dirname (file-name-as-directory dirname))
1980 (or (and (not switches)
1981 (dired-goto-subdir dirname))
1982 (dired-insert-subdir dirname switches no-error-if-not-dir-p))
1983 ;; Push mark so that it's easy to find back. Do this after the
1984 ;; insert message so that the user sees the `Mark set' message.
1985 (push-mark opoint)))
1987 ;;;###autoload
1988 (defun dired-insert-subdir (dirname &optional switches no-error-if-not-dir-p)
1989 "Insert this subdirectory into the same dired buffer.
1990 If it is already present, overwrites previous entry,
1991 else inserts it at its natural place (as `ls -lR' would have done).
1992 With a prefix arg, you may edit the `ls' switches used for this listing.
1993 You can add `R' to the switches to expand the whole tree starting at
1994 this subdirectory.
1995 This function takes some pains to conform to `ls -lR' output."
1996 ;; NO-ERROR-IF-NOT-DIR-P needed for special filesystems like
1997 ;; Prospero where dired-ls does the right thing, but
1998 ;; file-directory-p has not been redefined.
1999 (interactive
2000 (list (dired-get-filename)
2001 (if current-prefix-arg
2002 (read-string "Switches for listing: "
2003 (or dired-subdir-switches dired-actual-switches)))))
2004 (setq dirname (file-name-as-directory (expand-file-name dirname)))
2005 (or no-error-if-not-dir-p
2006 (file-directory-p dirname)
2007 (error "Attempt to insert a non-directory: %s" dirname))
2008 (let ((elt (assoc dirname dired-subdir-alist))
2009 (cons (assoc-string dirname dired-switches-alist))
2010 (modflag (buffer-modified-p))
2011 (old-switches switches)
2012 switches-have-R mark-alist case-fold-search buffer-read-only)
2013 (and (not switches) cons (setq switches (cdr cons)))
2014 (dired-insert-subdir-validate dirname switches)
2015 ;; case-fold-search is nil now, so we can test for capital `R':
2016 (if (setq switches-have-R (and switches (string-match "R" switches)))
2017 ;; avoid duplicated subdirs
2018 (setq mark-alist (dired-kill-tree dirname t)))
2019 (if elt
2020 ;; If subdir is already present, remove it and remember its marks
2021 (setq mark-alist (nconc (dired-insert-subdir-del elt) mark-alist))
2022 (dired-insert-subdir-newpos dirname)) ; else compute new position
2023 (dired-insert-subdir-doupdate
2024 dirname elt (dired-insert-subdir-doinsert dirname switches))
2025 (when old-switches
2026 (if cons
2027 (setcdr cons switches)
2028 (push (cons dirname switches) dired-switches-alist)))
2029 (when switches-have-R
2030 (dired-build-subdir-alist switches)
2031 (setq switches (dired-replace-in-string "R" "" switches))
2032 (dolist (cur-ass dired-subdir-alist)
2033 (let ((cur-dir (car cur-ass)))
2034 (and (dired-in-this-tree cur-dir dirname)
2035 (let ((cur-cons (assoc-string cur-dir dired-switches-alist)))
2036 (if cur-cons
2037 (setcdr cur-cons switches)
2038 (push (cons cur-dir switches) dired-switches-alist)))))))
2039 (dired-initial-position dirname)
2040 (save-excursion (dired-mark-remembered mark-alist))
2041 (restore-buffer-modified-p modflag)))
2043 (defun dired-insert-subdir-validate (dirname &optional switches)
2044 ;; Check that it is valid to insert DIRNAME with SWITCHES.
2045 ;; Signal an error if invalid (e.g. user typed `i' on `..').
2046 (or (dired-in-this-tree dirname (expand-file-name default-directory))
2047 (error "%s: not in this directory tree" dirname))
2048 (let ((real-switches (or switches dired-subdir-switches)))
2049 (when real-switches
2050 (let (case-fold-search)
2051 (mapcar
2052 (function
2053 (lambda (x)
2054 (or (eq (null (string-match x real-switches))
2055 (null (string-match x dired-actual-switches)))
2056 (error
2057 "Can't have dirs with and without -%s switches together" x))))
2058 ;; all switches that make a difference to dired-get-filename:
2059 '("F" "b"))))))
2061 (defun dired-alist-add (dir new-marker)
2062 ;; Add new DIR at NEW-MARKER. Sort alist.
2063 (dired-alist-add-1 dir new-marker)
2064 (dired-alist-sort))
2066 (defun dired-alist-sort ()
2067 ;; Keep the alist sorted on buffer position.
2068 (setq dired-subdir-alist
2069 (sort dired-subdir-alist
2070 (function (lambda (elt1 elt2)
2071 (> (dired-get-subdir-min elt1)
2072 (dired-get-subdir-min elt2)))))))
2074 (defun dired-kill-tree (dirname &optional remember-marks kill-root)
2075 "Kill all proper subdirs of DIRNAME, excluding DIRNAME itself.
2076 Interactively, you can kill DIRNAME as well by using a prefix argument.
2077 In interactive use, the command prompts for DIRNAME.
2079 When called from Lisp, if REMEMBER-MARKS is non-nil, return an alist
2080 of marked files. If KILL-ROOT is non-nil, kill DIRNAME as well."
2081 (interactive "DKill tree below directory: \ni\nP")
2082 (setq dirname (file-name-as-directory (expand-file-name dirname)))
2083 (let ((s-alist dired-subdir-alist) dir m-alist)
2084 (while s-alist
2085 (setq dir (car (car s-alist))
2086 s-alist (cdr s-alist))
2087 (and (or kill-root (not (string-equal dir dirname)))
2088 (dired-in-this-tree dir dirname)
2089 (dired-goto-subdir dir)
2090 (setq m-alist (nconc (dired-kill-subdir remember-marks) m-alist))))
2091 m-alist))
2093 (defun dired-insert-subdir-newpos (new-dir)
2094 ;; Find pos for new subdir, according to tree order.
2095 ;;(goto-char (point-max))
2096 (let ((alist dired-subdir-alist) elt dir pos new-pos)
2097 (while alist
2098 (setq elt (car alist)
2099 alist (cdr alist)
2100 dir (car elt))
2101 (if (dired-tree-lessp dir new-dir)
2102 ;; Insert NEW-DIR after DIR
2103 (setq new-pos (dired-get-subdir-max elt)
2104 alist nil)))
2105 (goto-char new-pos))
2106 ;; want a separating newline between subdirs
2107 (or (eobp)
2108 (forward-line -1))
2109 (insert "\n")
2110 (point))
2112 (defun dired-insert-subdir-del (element)
2113 ;; Erase an already present subdir (given by ELEMENT) from buffer.
2114 ;; Move to that buffer position. Return a mark-alist.
2115 (let ((begin-marker (dired-get-subdir-min element)))
2116 (goto-char begin-marker)
2117 ;; Are at beginning of subdir (and inside it!). Now determine its end:
2118 (goto-char (dired-subdir-max))
2119 (or (eobp);; want a separating newline _between_ subdirs:
2120 (forward-char -1))
2121 (prog1
2122 (dired-remember-marks begin-marker (point))
2123 (delete-region begin-marker (point)))))
2125 (defun dired-insert-subdir-doinsert (dirname switches)
2126 ;; Insert ls output after point.
2127 ;; Return the boundary of the inserted text (as list of BEG and END).
2128 (save-excursion
2129 (let ((begin (point)))
2130 (let ((dired-actual-switches
2131 (or switches
2132 dired-subdir-switches
2133 (dired-replace-in-string "R" "" dired-actual-switches))))
2134 (if (equal dirname (car (car (last dired-subdir-alist))))
2135 ;; If doing the top level directory of the buffer,
2136 ;; redo it as specified in dired-directory.
2137 (dired-readin-insert)
2138 (dired-insert-directory dirname dired-actual-switches nil nil t)))
2139 (list begin (point)))))
2141 (defun dired-insert-subdir-doupdate (dirname elt beg-end)
2142 ;; Point is at the correct subdir alist position for ELT,
2143 ;; BEG-END is the subdir-region (as list of begin and end).
2144 (if elt ; subdir was already present
2145 ;; update its position (should actually be unchanged)
2146 (set-marker (dired-get-subdir-min elt) (point-marker))
2147 (dired-alist-add dirname (point-marker)))
2148 ;; The hook may depend on the subdir-alist containing the just
2149 ;; inserted subdir, so run it after dired-alist-add:
2150 (if dired-after-readin-hook
2151 (save-excursion
2152 (let ((begin (nth 0 beg-end))
2153 (end (nth 1 beg-end)))
2154 (goto-char begin)
2155 (save-restriction
2156 (narrow-to-region begin end)
2157 ;; hook may add or delete lines, but the subdir boundary
2158 ;; marker floats
2159 (run-hooks 'dired-after-readin-hook))))))
2161 (defun dired-tree-lessp (dir1 dir2)
2162 ;; Lexicographic order on file name components, like `ls -lR':
2163 ;; DIR1 < DIR2 if DIR1 comes *before* DIR2 in an `ls -lR' listing,
2164 ;; i.e., if DIR1 is a (grand)parent dir of DIR2,
2165 ;; or DIR1 and DIR2 are in the same parentdir and their last
2166 ;; components are string-lessp.
2167 ;; Thus ("/usr/" "/usr/bin") and ("/usr/a/" "/usr/b/") are tree-lessp.
2168 ;; string-lessp could arguably be replaced by file-newer-than-file-p
2169 ;; if dired-actual-switches contained `t'.
2170 (setq dir1 (file-name-as-directory dir1)
2171 dir2 (file-name-as-directory dir2))
2172 (let ((components-1 (dired-split "/" dir1))
2173 (components-2 (dired-split "/" dir2)))
2174 (while (and components-1
2175 components-2
2176 (equal (car components-1) (car components-2)))
2177 (setq components-1 (cdr components-1)
2178 components-2 (cdr components-2)))
2179 (let ((c1 (car components-1))
2180 (c2 (car components-2)))
2182 (cond ((and c1 c2)
2183 (string-lessp c1 c2))
2184 ((and (null c1) (null c2))
2185 nil) ; they are equal, not lessp
2186 ((null c1) ; c2 is a subdir of c1: c1<c2
2188 ((null c2) ; c1 is a subdir of c2: c1>c2
2189 nil)
2190 (t (error "This can't happen"))))))
2192 ;; There should be a builtin split function - inverse to mapconcat.
2193 (defun dired-split (pat str &optional limit)
2194 "Splitting on regexp PAT, turn string STR into a list of substrings.
2195 Optional third arg LIMIT (>= 1) is a limit to the length of the
2196 resulting list.
2197 Thus, if SEP is a regexp that only matches itself,
2199 (mapconcat 'identity (dired-split SEP STRING) SEP)
2201 is always equal to STRING."
2202 (let* ((start (string-match pat str))
2203 (result (list (substring str 0 start)))
2204 (count 1)
2205 (end (if start (match-end 0))))
2206 (if end ; else nothing left
2207 (while (and (or (not (integerp limit))
2208 (< count limit))
2209 (string-match pat str end))
2210 (setq start (match-beginning 0)
2211 count (1+ count)
2212 result (cons (substring str end start) result)
2213 end (match-end 0)
2214 start end)
2216 (if (and (or (not (integerp limit))
2217 (< count limit))
2218 end) ; else nothing left
2219 (setq result
2220 (cons (substring str end) result)))
2221 (nreverse result)))
2223 ;;; moving by subdirectories
2225 ;;;###autoload
2226 (defun dired-prev-subdir (arg &optional no-error-if-not-found no-skip)
2227 "Go to previous subdirectory, regardless of level.
2228 When called interactively and not on a subdir line, go to this subdir's line."
2229 ;;(interactive "p")
2230 (interactive
2231 (list (if current-prefix-arg
2232 (prefix-numeric-value current-prefix-arg)
2233 ;; if on subdir start already, don't stay there!
2234 (if (dired-get-subdir) 1 0))))
2235 (dired-next-subdir (- arg) no-error-if-not-found no-skip))
2237 (defun dired-subdir-min ()
2238 (save-excursion
2239 (if (not (dired-prev-subdir 0 t t))
2240 (error "Not in a subdir!")
2241 (point))))
2243 ;;;###autoload
2244 (defun dired-goto-subdir (dir)
2245 "Go to end of header line of DIR in this dired buffer.
2246 Return value of point on success, otherwise return nil.
2247 The next char is either \\n, or \\r if DIR is hidden."
2248 (interactive
2249 (prog1 ; let push-mark display its message
2250 (list (expand-file-name
2251 (completing-read "Goto in situ directory: " ; prompt
2252 dired-subdir-alist ; table
2253 nil ; predicate
2254 t ; require-match
2255 (dired-current-directory))))
2256 (push-mark)))
2257 (setq dir (file-name-as-directory dir))
2258 (let ((elt (assoc dir dired-subdir-alist)))
2259 (and elt
2260 (goto-char (dired-get-subdir-min elt))
2261 ;; dired-subdir-hidden-p and dired-add-entry depend on point being
2262 ;; at either \r or \n after this function succeeds.
2263 (progn (skip-chars-forward "^\r\n")
2264 (point)))))
2266 ;;;###autoload
2267 (defun dired-mark-subdir-files ()
2268 "Mark all files except `.' and `..' in current subdirectory.
2269 If the Dired buffer shows multiple directories, this command
2270 marks the files listed in the subdirectory that point is in."
2271 (interactive)
2272 (let ((p-min (dired-subdir-min)))
2273 (dired-mark-files-in-region p-min (dired-subdir-max))))
2275 ;;;###autoload
2276 (defun dired-kill-subdir (&optional remember-marks)
2277 "Remove all lines of current subdirectory.
2278 Lower levels are unaffected."
2279 ;; With optional REMEMBER-MARKS, return a mark-alist.
2280 (interactive)
2281 (let* ((beg (dired-subdir-min))
2282 (end (dired-subdir-max))
2283 (modflag (buffer-modified-p))
2284 (cur-dir (dired-current-directory))
2285 (cons (assoc-string cur-dir dired-switches-alist))
2286 buffer-read-only)
2287 (if (equal cur-dir default-directory)
2288 (error "Attempt to kill top level directory"))
2289 (prog1
2290 (if remember-marks (dired-remember-marks beg end))
2291 (delete-region beg end)
2292 (if (eobp) ; don't leave final blank line
2293 (delete-char -1))
2294 (dired-unsubdir cur-dir)
2295 (when cons
2296 (setq dired-switches-alist (delete cons dired-switches-alist)))
2297 (restore-buffer-modified-p modflag))))
2299 (defun dired-unsubdir (dir)
2300 ;; Remove DIR from the alist
2301 (setq dired-subdir-alist
2302 (delq (assoc dir dired-subdir-alist) dired-subdir-alist)))
2304 ;;;###autoload
2305 (defun dired-tree-up (arg)
2306 "Go up ARG levels in the dired tree."
2307 (interactive "p")
2308 (let ((dir (dired-current-directory)))
2309 (while (>= arg 1)
2310 (setq arg (1- arg)
2311 dir (file-name-directory (directory-file-name dir))))
2312 ;;(setq dir (expand-file-name dir))
2313 (or (dired-goto-subdir dir)
2314 (error "Cannot go up to %s - not in this tree" dir))))
2316 ;;;###autoload
2317 (defun dired-tree-down ()
2318 "Go down in the dired tree."
2319 (interactive)
2320 (let ((dir (dired-current-directory)) ; has slash
2321 pos case-fold-search) ; filenames are case sensitive
2322 (let ((rest (reverse dired-subdir-alist)) elt)
2323 (while rest
2324 (setq elt (car rest)
2325 rest (cdr rest))
2326 (if (dired-in-this-tree (directory-file-name (car elt)) dir)
2327 (setq rest nil
2328 pos (dired-goto-subdir (car elt))))))
2329 (if pos
2330 (goto-char pos)
2331 (error "At the bottom"))))
2333 ;;; hiding
2335 (defun dired-unhide-subdir ()
2336 (let (buffer-read-only)
2337 (subst-char-in-region (dired-subdir-min) (dired-subdir-max) ?\r ?\n)))
2339 (defun dired-hide-check ()
2340 (or selective-display
2341 (error "selective-display must be t for subdir hiding to work!")))
2343 (defun dired-subdir-hidden-p (dir)
2344 (and selective-display
2345 (save-excursion
2346 (dired-goto-subdir dir)
2347 (looking-at "\r"))))
2349 ;;;###autoload
2350 (defun dired-hide-subdir (arg)
2351 "Hide or unhide the current subdirectory and move to next directory.
2352 Optional prefix arg is a repeat factor.
2353 Use \\[dired-hide-all] to (un)hide all directories."
2354 (interactive "p")
2355 (dired-hide-check)
2356 (let ((modflag (buffer-modified-p)))
2357 (while (>= (setq arg (1- arg)) 0)
2358 (let* ((cur-dir (dired-current-directory))
2359 (hidden-p (dired-subdir-hidden-p cur-dir))
2360 (elt (assoc cur-dir dired-subdir-alist))
2361 (end-pos (1- (dired-get-subdir-max elt)))
2362 buffer-read-only)
2363 ;; keep header line visible, hide rest
2364 (goto-char (dired-get-subdir-min elt))
2365 (skip-chars-forward "^\n\r")
2366 (if hidden-p
2367 (subst-char-in-region (point) end-pos ?\r ?\n)
2368 (subst-char-in-region (point) end-pos ?\n ?\r)))
2369 (dired-next-subdir 1 t))
2370 (restore-buffer-modified-p modflag)))
2372 ;;;###autoload
2373 (defun dired-hide-all (&optional ignored)
2374 "Hide all subdirectories, leaving only their header lines.
2375 If there is already something hidden, make everything visible again.
2376 Use \\[dired-hide-subdir] to (un)hide a particular subdirectory."
2377 (interactive "P")
2378 (dired-hide-check)
2379 (let ((modflag (buffer-modified-p))
2380 buffer-read-only)
2381 (if (save-excursion
2382 (goto-char (point-min))
2383 (search-forward "\r" nil t))
2384 ;; unhide - bombs on \r in filenames
2385 (subst-char-in-region (point-min) (point-max) ?\r ?\n)
2386 ;; hide
2387 (let ((pos (point-max)) ; pos of end of last directory
2388 (alist dired-subdir-alist))
2389 (while alist ; while there are dirs before pos
2390 (subst-char-in-region (dired-get-subdir-min (car alist)) ; pos of prev dir
2391 (save-excursion
2392 (goto-char pos) ; current dir
2393 ;; we're somewhere on current dir's line
2394 (forward-line -1)
2395 (point))
2396 ?\n ?\r)
2397 (setq pos (dired-get-subdir-min (car alist))) ; prev dir gets current dir
2398 (setq alist (cdr alist)))))
2399 (restore-buffer-modified-p modflag)))
2401 ;;;###end dired-ins.el
2404 ;; Search only in file names in the Dired buffer.
2406 (defcustom dired-isearch-filenames nil
2407 "Non-nil to Isearch in file names only.
2408 If t, Isearch in Dired always matches only file names.
2409 If `dwim', Isearch matches file names when initial point position is on
2410 a file name. Otherwise, it searches the whole buffer without restrictions."
2411 :type '(choice (const :tag "No restrictions" nil)
2412 (const :tag "When point is on a file name initially, search file names" dwim)
2413 (const :tag "Always search in file names" t))
2414 :group 'dired
2415 :version "23.1")
2417 (defvar dired-isearch-filter-predicate-orig nil)
2419 (defun dired-isearch-filenames-toggle ()
2420 "Toggle file names searching on or off.
2421 When on, Isearch skips matches outside file names using the predicate
2422 `dired-isearch-filter-filenames' that matches only at file names.
2423 When off, it uses the original predicate."
2424 (interactive)
2425 (setq isearch-filter-predicate
2426 (if (eq isearch-filter-predicate 'dired-isearch-filter-filenames)
2427 dired-isearch-filter-predicate-orig
2428 'dired-isearch-filter-filenames))
2429 (setq isearch-success t isearch-adjusted t)
2430 (isearch-update))
2432 ;;;###autoload
2433 (defun dired-isearch-filenames-setup ()
2434 "Set up isearch to search in Dired file names.
2435 Intended to be added to `isearch-mode-hook'."
2436 (when (or (eq dired-isearch-filenames t)
2437 (and (eq dired-isearch-filenames 'dwim)
2438 (get-text-property (point) 'dired-filename)))
2439 (setq isearch-message-prefix-add "filename ")
2440 (define-key isearch-mode-map "\M-sf" 'dired-isearch-filenames-toggle)
2441 (setq dired-isearch-filter-predicate-orig
2442 (default-value 'isearch-filter-predicate))
2443 (setq-default isearch-filter-predicate 'dired-isearch-filter-filenames)
2444 (add-hook 'isearch-mode-end-hook 'dired-isearch-filenames-end nil t)))
2446 (defun dired-isearch-filenames-end ()
2447 "Clean up the Dired file name search after terminating isearch."
2448 (setq isearch-message-prefix-add nil)
2449 (define-key isearch-mode-map "\M-sf" nil)
2450 (setq-default isearch-filter-predicate dired-isearch-filter-predicate-orig)
2451 (remove-hook 'isearch-mode-end-hook 'dired-isearch-filenames-end t))
2453 (defun dired-isearch-filter-filenames (beg end)
2454 "Test whether the current search hit is a visible file name.
2455 Return non-nil if the text from BEG to END is part of a file
2456 name (has the text property `dired-filename') and is visible."
2457 (and (isearch-filter-visible beg end)
2458 (if dired-isearch-filenames
2459 (text-property-not-all (min beg end) (max beg end)
2460 'dired-filename nil)
2461 t)))
2463 ;;;###autoload
2464 (defun dired-isearch-filenames ()
2465 "Search for a string using Isearch only in file names in the Dired buffer."
2466 (interactive)
2467 (let ((dired-isearch-filenames t))
2468 (isearch-forward)))
2470 ;;;###autoload
2471 (defun dired-isearch-filenames-regexp ()
2472 "Search for a regexp using Isearch only in file names in the Dired buffer."
2473 (interactive)
2474 (let ((dired-isearch-filenames t))
2475 (isearch-forward-regexp)))
2478 ;; Functions for searching in tags style among marked files.
2480 ;;;###autoload
2481 (defun dired-do-isearch ()
2482 "Search for a string through all marked files using Isearch."
2483 (interactive)
2484 (multi-isearch-files
2485 (dired-get-marked-files nil nil 'dired-nondirectory-p)))
2487 ;;;###autoload
2488 (defun dired-do-isearch-regexp ()
2489 "Search for a regexp through all marked files using Isearch."
2490 (interactive)
2491 (multi-isearch-files-regexp
2492 (dired-get-marked-files nil nil 'dired-nondirectory-p)))
2494 ;;;###autoload
2495 (defun dired-do-search (regexp)
2496 "Search through all marked files for a match for REGEXP.
2497 Stops when a match is found.
2498 To continue searching for next match, use command \\[tags-loop-continue]."
2499 (interactive "sSearch marked files (regexp): ")
2500 (tags-search regexp '(dired-get-marked-files nil nil 'dired-nondirectory-p)))
2502 ;;;###autoload
2503 (defun dired-do-query-replace-regexp (from to &optional delimited)
2504 "Do `query-replace-regexp' of FROM with TO, on all marked files.
2505 Third arg DELIMITED (prefix arg) means replace only word-delimited matches.
2506 If you exit (\\[keyboard-quit], RET or q), you can resume the query replace
2507 with the command \\[tags-loop-continue]."
2508 (interactive
2509 (let ((common
2510 (query-replace-read-args
2511 "Query replace regexp in marked files" t t)))
2512 (list (nth 0 common) (nth 1 common) (nth 2 common))))
2513 (dolist (file (dired-get-marked-files nil nil 'dired-nondirectory-p))
2514 (let ((buffer (get-file-buffer file)))
2515 (if (and buffer (with-current-buffer buffer
2516 buffer-read-only))
2517 (error "File `%s' is visited read-only" file))))
2518 (tags-query-replace from to delimited
2519 '(dired-get-marked-files nil nil 'dired-nondirectory-p)))
2521 (defun dired-nondirectory-p (file)
2522 (not (file-directory-p file)))
2524 ;;;###autoload
2525 (defun dired-show-file-type (file &optional deref-symlinks)
2526 "Print the type of FILE, according to the `file' command.
2527 If you give a prefix to this command, and FILE is a symbolic
2528 link, then the type of the file linked to by FILE is printed
2529 instead."
2530 (interactive (list (dired-get-filename t) current-prefix-arg))
2531 (let (process-file-side-effects)
2532 (with-temp-buffer
2533 (if deref-symlinks
2534 (process-file "file" nil t t "-L" "--" file)
2535 (process-file "file" nil t t "--" file))
2536 (when (bolp)
2537 (backward-delete-char 1))
2538 (message "%s" (buffer-string)))))
2540 (provide 'dired-aux)
2542 ;; Local Variables:
2543 ;; byte-compile-dynamic: t
2544 ;; generated-autoload-file: "dired.el"
2545 ;; End:
2547 ;;; dired-aux.el ends here