2d05be312eb1bcf542f83aa79af282002dc6a769
[bpt/emacs.git] / lisp / dired-aux.el
1 ;;; dired-aux.el --- less commonly used parts of dired
2
3 ;; Copyright (C) 1985-1986, 1992, 1994, 1998, 2000-2012
4 ;; Free Software Foundation, Inc.
5
6 ;; Author: Sebastian Kremer <sk@thp.uni-koeln.de>.
7 ;; Maintainer: FSF
8 ;; Keywords: files
9 ;; Package: emacs
10
11 ;; This file is part of GNU Emacs.
12
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.
17
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.
22
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/>.
25
26 ;;; Commentary:
27
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.
31
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.
35
36 ;;; Code:
37
38 ;; We need macros in dired.el to compile properly,
39 ;; and we call subroutines in it too.
40 (require 'dired)
41
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.")
46
47 ;;; 15K
48 ;;;###begin dired-cmd.el
49 ;; Diffing and compressing
50
51 (defconst dired-star-subst-regexp "\\(^\\|[ \t]\\)\\*\\([ \t]\\|$\\)")
52 (defconst dired-quark-subst-regexp "\\(^\\|[ \t]\\)\\?\\([ \t]\\|$\\)")
53
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)))
102
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))
118
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).
127
128 PREDICATE is a Lisp expression that can refer to the following variables:
129
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'
134
135 where 1 refers to attribute of file in the current dired buffer
136 and 2 to attribute of file in second dired buffer.
137
138 Examples of PREDICATE:
139
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))))
188
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))))
217
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)))
228 \f
229 ;;; Change file attributes
230
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))))
268
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))))
296
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)))
303
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))
311
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))
319
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))
326
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))))
368
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))))
386
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).
391
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.
396
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))
405 \f
406 ;;; Cleaning a directory: flagging some backups for deletion.
407
408 (defvar dired-file-version-alist)
409
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.
416
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")))
448
449 ;;; Subroutines of dired-clean-directory.
450
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)))))
465
466 (defvar backup-extract-version-start) ; used in backup-extract-version
467
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)
472 nil
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)))))))
487
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)))))
500 \f
501 ;;; Shell commands
502
503 (declare-function mailcap-file-default-commands "mailcap" (files))
504
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))))
515
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.
523
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))))
537
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.
541
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))
557
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.
566
567 If there is a `*' in COMMAND, surrounded by whitespace, this runs
568 COMMAND just once with the entire file list substituted there.
569
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 `?'.
573
574 Otherwise, this runs COMMAND on each file individually with the
575 file name added at the end of COMMAND (separated by a space).
576
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.
580
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.
584
585 If COMMAND produces output, it goes to a separate buffer.
586
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.
590
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.
594
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))))
629 nil
630 file-list)
631 ;; execute the shell command
632 (dired-run-shell-command
633 (dired-shell-stuff-it command file-list nil arg))))))
634
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.")
642
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)))))
668
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)
679 \f
680
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))))
705 \f
706 ;; Commands that delete or redisplay part of the dired buffer.
707
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)))
729
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))))
761
762 ;;;###end dired-cmd.el
763 \f
764 ;;; 30K
765 ;;;###begin dired-cp.el
766
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)))
784
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.")
807
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))
835 (t
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"))))))))
860 \f
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) "? ")))))
878
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.
882
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'.
886
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")')
891
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)))))
909
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.
914
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.
918
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)))))
937
938 \f
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))
944
945 ;; Commands for Emacs Lisp files - load and byte compile
946
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)))
966
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))
972
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)
980 nil
981 (dired-log "Load error for %s:\n%s\n" file failure)
982 (dired-make-relative file))))
983
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))
989
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.
995
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
1009 dir
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")))
1029
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))
1035 \f
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))
1053
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))
1059
1060 (defvar dired-omit-mode)
1061 (declare-function dired-omit-regexp "dired-x" ())
1062 (defvar dired-omit-localp)
1063
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.
1071
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))
1085 (t
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).
1176 t))
1177
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)))
1190
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))
1196
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))))))
1203
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))
1210
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)))))
1226 \f
1227 ;;; Copy, move/rename, making hard and symbolic links
1228
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)
1236
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)
1241
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))))
1256
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))
1262
1263 (declare-function make-symbolic-link "fileio.c")
1264
1265 (defun dired-copy-file-recursive (from to ok-flag &optional
1266 preserve-time top recursive)
1267 (let ((attrs (file-attributes from)))
1268 (if (and recursive
1269 (eq t (car attrs))
1270 (or (eq recursive 'always)
1271 (yes-or-no-p (format "Recursive copies of %s? " from))))
1272 ;; This is a directory.
1273 (copy-directory from to preserve-time)
1274 ;; Not a directory.
1275 (or top (dired-handle-overwrite to))
1276 (condition-case err
1277 (if (stringp (car attrs))
1278 ;; It is a symlink
1279 (make-symbolic-link (car attrs) to ok-flag)
1280 (copy-file from to ok-flag preserve-time))
1281 (file-date-error
1282 (push (dired-make-relative from)
1283 dired-create-files-failures)
1284 (dired-log "Can't set date on %s:\n%s\n" from err))))))
1285
1286 ;;;###autoload
1287 (defun dired-rename-file (file newname ok-if-already-exists)
1288 (dired-handle-overwrite newname)
1289 (rename-file file newname ok-if-already-exists) ; error is caught in -create-files
1290 ;; Silently rename the visited file of any buffer visiting this file.
1291 (and (get-file-buffer file)
1292 (with-current-buffer (get-file-buffer file)
1293 (set-visited-file-name newname nil t)))
1294 (dired-remove-file file)
1295 ;; See if it's an inserted subdir, and rename that, too.
1296 (dired-rename-subdir file newname))
1297
1298 (defun dired-rename-subdir (from-dir to-dir)
1299 (setq from-dir (file-name-as-directory from-dir)
1300 to-dir (file-name-as-directory to-dir))
1301 (dired-fun-in-all-buffers from-dir nil
1302 (function dired-rename-subdir-1) from-dir to-dir)
1303 ;; Update visited file name of all affected buffers
1304 (let ((expanded-from-dir (expand-file-name from-dir))
1305 (blist (buffer-list)))
1306 (while blist
1307 (with-current-buffer (car blist)
1308 (if (and buffer-file-name
1309 (dired-in-this-tree buffer-file-name expanded-from-dir))
1310 (let ((modflag (buffer-modified-p))
1311 (to-file (dired-replace-in-string
1312 (concat "^" (regexp-quote from-dir))
1313 to-dir
1314 buffer-file-name)))
1315 (set-visited-file-name to-file)
1316 (set-buffer-modified-p modflag))))
1317 (setq blist (cdr blist)))))
1318
1319 (defun dired-rename-subdir-1 (dir to)
1320 ;; Rename DIR to TO in headerlines and dired-subdir-alist, if DIR or
1321 ;; one of its subdirectories is expanded in this buffer.
1322 (let ((expanded-dir (expand-file-name dir))
1323 (alist dired-subdir-alist)
1324 (elt nil))
1325 (while alist
1326 (setq elt (car alist)
1327 alist (cdr alist))
1328 (if (dired-in-this-tree (car elt) expanded-dir)
1329 ;; ELT's subdir is affected by the rename
1330 (dired-rename-subdir-2 elt dir to)))
1331 (if (equal dir default-directory)
1332 ;; if top level directory was renamed, lots of things have to be
1333 ;; updated:
1334 (progn
1335 (dired-unadvertise dir) ; we no longer dired DIR...
1336 (setq default-directory to
1337 dired-directory (expand-file-name;; this is correct
1338 ;; with and without wildcards
1339 (file-name-nondirectory dired-directory)
1340 to))
1341 (let ((new-name (file-name-nondirectory
1342 (directory-file-name dired-directory))))
1343 ;; try to rename buffer, but just leave old name if new
1344 ;; name would already exist (don't try appending "<%d>")
1345 (or (get-buffer new-name)
1346 (rename-buffer new-name)))
1347 ;; ... we dired TO now:
1348 (dired-advertise)))))
1349
1350 (defun dired-rename-subdir-2 (elt dir to)
1351 ;; Update the headerline and dired-subdir-alist element, as well as
1352 ;; dired-switches-alist element, of directory described by
1353 ;; alist-element ELT to reflect the moving of DIR to TO. Thus, ELT
1354 ;; describes either DIR itself or a subdir of DIR.
1355 (save-excursion
1356 (let ((regexp (regexp-quote (directory-file-name dir)))
1357 (newtext (directory-file-name to))
1358 buffer-read-only)
1359 (goto-char (dired-get-subdir-min elt))
1360 ;; Update subdir headerline in buffer
1361 (if (not (looking-at dired-subdir-regexp))
1362 (error "%s not found where expected - dired-subdir-alist broken?"
1363 dir)
1364 (goto-char (match-beginning 1))
1365 (if (re-search-forward regexp (match-end 1) t)
1366 (replace-match newtext t t)
1367 (error "Expected to find `%s' in headerline of %s" dir (car elt))))
1368 ;; Update buffer-local dired-subdir-alist and dired-switches-alist
1369 (let ((cons (assoc-string (car elt) dired-switches-alist))
1370 (cur-dir (dired-normalize-subdir
1371 (dired-replace-in-string regexp newtext (car elt)))))
1372 (setcar elt cur-dir)
1373 (when cons (setcar cons cur-dir))))))
1374 \f
1375 ;; Bound in dired-create-files
1376 (defvar overwrite-query)
1377 (defvar overwrite-backup-query)
1378
1379 ;; The basic function for half a dozen variations on cp/mv/ln/ln -s.
1380 (defun dired-create-files (file-creator operation fn-list name-constructor
1381 &optional marker-char)
1382 "Create one or more new files from a list of existing files FN-LIST.
1383 This function also handles querying the user, updating Dired
1384 buffers, and displaying a success or failure message.
1385
1386 FILE-CREATOR should be a function. It is called once for each
1387 file in FN-LIST, and must create a new file, querying the user
1388 and updating Dired buffers as necessary. It should accept three
1389 arguments: the old file name, the new name, and an argument
1390 OK-IF-ALREADY-EXISTS with the same meaning as in `copy-file'.
1391
1392 OPERATION should be a capitalized string describing the operation
1393 performed (e.g. `Copy'). It is used for error logging.
1394
1395 FN-LIST is the list of files to copy (full absolute file names).
1396
1397 NAME-CONSTRUCTOR should be a function accepting a single
1398 argument, the name of an old file, and returning either the
1399 corresponding new file name or nil to skip.
1400
1401 Optional MARKER-CHAR is a character with which to mark every
1402 newfile's entry, or t to use the current marker character if the
1403 old file was marked."
1404 (let (dired-create-files-failures failures
1405 skipped (success-count 0) (total (length fn-list)))
1406 (let (to overwrite-query
1407 overwrite-backup-query) ; for dired-handle-overwrite
1408 (dolist (from fn-list)
1409 (setq to (funcall name-constructor from))
1410 (if (equal to from)
1411 (progn
1412 (setq to nil)
1413 (dired-log "Cannot %s to same file: %s\n"
1414 (downcase operation) from)))
1415 (if (not to)
1416 (setq skipped (cons (dired-make-relative from) skipped))
1417 (let* ((overwrite (file-exists-p to))
1418 (dired-overwrite-confirmed ; for dired-handle-overwrite
1419 (and overwrite
1420 (let ((help-form '(format "\
1421 Type SPC or `y' to overwrite file `%s',
1422 DEL or `n' to skip to next,
1423 ESC or `q' to not overwrite any of the remaining files,
1424 `!' to overwrite all remaining files with no more questions." to)))
1425 (dired-query 'overwrite-query
1426 "Overwrite `%s'?" to))))
1427 ;; must determine if FROM is marked before file-creator
1428 ;; gets a chance to delete it (in case of a move).
1429 (actual-marker-char
1430 (cond ((integerp marker-char) marker-char)
1431 (marker-char (dired-file-marker from)) ; slow
1432 (t nil))))
1433 (when (and (file-directory-p from)
1434 (file-directory-p to)
1435 (eq file-creator 'dired-copy-file))
1436 (setq to (file-name-directory to)))
1437 (condition-case err
1438 (progn
1439 (funcall file-creator from to dired-overwrite-confirmed)
1440 (if overwrite
1441 ;; If we get here, file-creator hasn't been aborted
1442 ;; and the old entry (if any) has to be deleted
1443 ;; before adding the new entry.
1444 (dired-remove-file to))
1445 (setq success-count (1+ success-count))
1446 (message "%s: %d of %d" operation success-count total)
1447 (dired-add-file to actual-marker-char))
1448 (file-error ; FILE-CREATOR aborted
1449 (progn
1450 (push (dired-make-relative from)
1451 failures)
1452 (dired-log "%s `%s' to `%s' failed:\n%s\n"
1453 operation from to err))))))))
1454 (cond
1455 (dired-create-files-failures
1456 (setq failures (nconc failures dired-create-files-failures))
1457 (dired-log-summary
1458 (format "%s failed for %d file%s in %d requests"
1459 operation (length failures)
1460 (dired-plural-s (length failures))
1461 total)
1462 failures))
1463 (failures
1464 (dired-log-summary
1465 (format "%s failed for %d of %d file%s"
1466 operation (length failures)
1467 total (dired-plural-s total))
1468 failures))
1469 (skipped
1470 (dired-log-summary
1471 (format "%s: %d of %d file%s skipped"
1472 operation (length skipped) total
1473 (dired-plural-s total))
1474 skipped))
1475 (t
1476 (message "%s: %s file%s"
1477 operation success-count (dired-plural-s success-count)))))
1478 (dired-move-to-filename))
1479 \f
1480 (defun dired-do-create-files (op-symbol file-creator operation arg
1481 &optional marker-char op1
1482 how-to)
1483 "Create a new file for each marked file.
1484 Prompts user for target, which is a directory in which to create
1485 the new files. Target may also be a plain file if only one marked
1486 file exists. The way the default for the target directory is
1487 computed depends on the value of `dired-dwim-target-directory'.
1488 OP-SYMBOL is the symbol for the operation. Function `dired-mark-pop-up'
1489 will determine whether pop-ups are appropriate for this OP-SYMBOL.
1490 FILE-CREATOR and OPERATION as in `dired-create-files'.
1491 ARG as in `dired-get-marked-files'.
1492 Optional arg MARKER-CHAR as in `dired-create-files'.
1493 Optional arg OP1 is an alternate form for OPERATION if there is
1494 only one file.
1495 Optional arg HOW-TO determines how to treat the target.
1496 If HOW-TO is nil, use `file-directory-p' to determine if the
1497 target is a directory. If so, the marked file(s) are created
1498 inside that directory. Otherwise, the target is a plain file;
1499 an error is raised unless there is exactly one marked file.
1500 If HOW-TO is t, target is always treated as a plain file.
1501 Otherwise, HOW-TO should be a function of one argument, TARGET.
1502 If its return value is nil, TARGET is regarded as a plain file.
1503 If it return value is a list, TARGET is a generalized
1504 directory (e.g. some sort of archive). The first element of
1505 this list must be a function with at least four arguments:
1506 operation - as OPERATION above.
1507 rfn-list - list of the relative names for the marked files.
1508 fn-list - list of the absolute names for the marked files.
1509 target - the name of the target itself.
1510 The rest of into-dir are optional arguments.
1511 For any other return value, TARGET is treated as a directory."
1512 (or op1 (setq op1 operation))
1513 (let* ((fn-list (dired-get-marked-files nil arg))
1514 (rfn-list (mapcar (function dired-make-relative) fn-list))
1515 (dired-one-file ; fluid variable inside dired-create-files
1516 (and (consp fn-list) (null (cdr fn-list)) (car fn-list)))
1517 (target-dir (dired-dwim-target-directory))
1518 (default (and dired-one-file
1519 (expand-file-name (file-name-nondirectory (car fn-list))
1520 target-dir)))
1521 (defaults (dired-dwim-target-defaults fn-list target-dir))
1522 (target (expand-file-name ; fluid variable inside dired-create-files
1523 (minibuffer-with-setup-hook
1524 (lambda ()
1525 (set (make-local-variable 'minibuffer-default-add-function) nil)
1526 (setq minibuffer-default defaults))
1527 (dired-mark-read-file-name
1528 (concat (if dired-one-file op1 operation) " %s to: ")
1529 target-dir op-symbol arg rfn-list default))))
1530 (into-dir (cond ((null how-to)
1531 ;; Allow DOS/Windows users to change the letter
1532 ;; case of a directory. If we don't test these
1533 ;; conditions up front, file-directory-p below
1534 ;; will return t because the filesystem is
1535 ;; case-insensitive, and Emacs will try to move
1536 ;; foo -> foo/foo, which fails.
1537 (if (and (memq system-type '(ms-dos windows-nt cygwin))
1538 (eq op-symbol 'move)
1539 dired-one-file
1540 (string= (downcase
1541 (expand-file-name (car fn-list)))
1542 (downcase
1543 (expand-file-name target)))
1544 (not (string=
1545 (file-name-nondirectory (car fn-list))
1546 (file-name-nondirectory target))))
1547 nil
1548 (file-directory-p target)))
1549 ((eq how-to t) nil)
1550 (t (funcall how-to target)))))
1551 (if (and (consp into-dir) (functionp (car into-dir)))
1552 (apply (car into-dir) operation rfn-list fn-list target (cdr into-dir))
1553 (if (not (or dired-one-file into-dir))
1554 (error "Marked %s: target must be a directory: %s" operation target))
1555 ;; rename-file bombs when moving directories unless we do this:
1556 (or into-dir (setq target (directory-file-name target)))
1557 (dired-create-files
1558 file-creator operation fn-list
1559 (if into-dir ; target is a directory
1560 ;; This function uses fluid variable target when called
1561 ;; inside dired-create-files:
1562 (function
1563 (lambda (from)
1564 (expand-file-name (file-name-nondirectory from) target)))
1565 (function (lambda (_from) target)))
1566 marker-char))))
1567
1568 ;; Read arguments for a marked-files command that wants a file name,
1569 ;; perhaps popping up the list of marked files.
1570 ;; ARG is the prefix arg and indicates whether the files came from
1571 ;; marks (ARG=nil) or a repeat factor (integerp ARG).
1572 ;; If the current file was used, the list has but one element and ARG
1573 ;; does not matter. (It is non-nil, non-integer in that case, namely '(4)).
1574 ;; DEFAULT is the default value to return if the user just hits RET;
1575 ;; if it is omitted or nil, then the name of the directory is used.
1576
1577 (defun dired-mark-read-file-name (prompt dir op-symbol arg files
1578 &optional default)
1579 (dired-mark-pop-up
1580 nil op-symbol files
1581 (function read-file-name)
1582 (format prompt (dired-mark-prompt arg files)) dir default))
1583
1584 (defun dired-dwim-target-directory ()
1585 ;; Try to guess which target directory the user may want.
1586 ;; If there is a dired buffer displayed in one of the next windows,
1587 ;; use its current subdir, else use current subdir of this dired buffer.
1588 (let ((this-dir (and (eq major-mode 'dired-mode)
1589 (dired-current-directory))))
1590 ;; non-dired buffer may want to profit from this function, e.g. vm-uudecode
1591 (if dired-dwim-target
1592 (let* ((other-win (get-window-with-predicate
1593 (lambda (window)
1594 (with-current-buffer (window-buffer window)
1595 (eq major-mode 'dired-mode)))))
1596 (other-dir (and other-win
1597 (with-current-buffer (window-buffer other-win)
1598 (and (eq major-mode 'dired-mode)
1599 (dired-current-directory))))))
1600 (or other-dir this-dir))
1601 this-dir)))
1602
1603 (defun dired-dwim-target-defaults (fn-list target-dir)
1604 ;; Return a list of default values for file-reading functions in Dired.
1605 ;; This list may contain directories from Dired buffers in other windows.
1606 ;; `fn-list' is a list of file names used to build a list of defaults.
1607 ;; When nil or more than one element, a list of defaults will
1608 ;; contain only directory names. `target-dir' is a directory name
1609 ;; to exclude from the returned list, for the case when this
1610 ;; directory name is already presented in initial input.
1611 ;; For Dired operations that support `dired-dwim-target',
1612 ;; the argument `target-dir' should have the value returned
1613 ;; from `dired-dwim-target-directory'.
1614 (let ((dired-one-file
1615 (and (consp fn-list) (null (cdr fn-list)) (car fn-list)))
1616 (current-dir (and (eq major-mode 'dired-mode)
1617 (dired-current-directory)))
1618 dired-dirs)
1619 ;; Get a list of directories of visible buffers in dired-mode.
1620 (walk-windows (lambda (w)
1621 (with-current-buffer (window-buffer w)
1622 (and (eq major-mode 'dired-mode)
1623 (push (dired-current-directory) dired-dirs)))))
1624 ;; Force the current dir to be the first in the list.
1625 (setq dired-dirs
1626 (delete-dups (delq nil (cons current-dir (nreverse dired-dirs)))))
1627 ;; Remove the target dir (if specified) or the current dir from
1628 ;; default values, because it should be already in initial input.
1629 (setq dired-dirs (delete (or target-dir current-dir) dired-dirs))
1630 ;; Return a list of default values.
1631 (if dired-one-file
1632 ;; For one file operation, provide a list that contains
1633 ;; other directories, other directories with the appended filename
1634 ;; and the current directory with the appended filename, e.g.
1635 ;; 1. /TARGET-DIR/
1636 ;; 2. /TARGET-DIR/FILENAME
1637 ;; 3. /CURRENT-DIR/FILENAME
1638 (append dired-dirs
1639 (mapcar (lambda (dir)
1640 (expand-file-name
1641 (file-name-nondirectory (car fn-list)) dir))
1642 (reverse dired-dirs))
1643 (list (expand-file-name
1644 (file-name-nondirectory (car fn-list))
1645 (or target-dir current-dir))))
1646 ;; For multi-file operation, return only a list of other directories.
1647 dired-dirs)))
1648
1649 \f
1650 ;;;###autoload
1651 (defun dired-create-directory (directory)
1652 "Create a directory called DIRECTORY.
1653 If DIRECTORY already exists, signal an error."
1654 (interactive
1655 (list (read-file-name "Create directory: " (dired-current-directory))))
1656 (let* ((expanded (directory-file-name (expand-file-name directory)))
1657 (try expanded) new)
1658 (if (file-exists-p expanded)
1659 (error "Cannot create directory %s: file exists" expanded))
1660 ;; Find the topmost nonexistent parent dir (variable `new')
1661 (while (and try (not (file-exists-p try)) (not (equal new try)))
1662 (setq new try
1663 try (directory-file-name (file-name-directory try))))
1664 (make-directory expanded t)
1665 (when new
1666 (dired-add-file new)
1667 (dired-move-to-filename))))
1668
1669 (defun dired-into-dir-with-symlinks (target)
1670 (and (file-directory-p target)
1671 (not (file-symlink-p target))))
1672 ;; This may not always be what you want, especially if target is your
1673 ;; home directory and it happens to be a symbolic link, as is often the
1674 ;; case with NFS and automounters. Or if you want to make symlinks
1675 ;; into directories that themselves are only symlinks, also quite
1676 ;; common.
1677
1678 ;; So we don't use this function as value for HOW-TO in
1679 ;; dired-do-symlink, which has the minor disadvantage of
1680 ;; making links *into* a symlinked-dir, when you really wanted to
1681 ;; *overwrite* that symlink. In that (rare, I guess) case, you'll
1682 ;; just have to remove that symlink by hand before making your marked
1683 ;; symlinks.
1684
1685 (defvar dired-copy-how-to-fn nil
1686 "Either nil or a function used by `dired-do-copy' to determine target.
1687 See HOW-TO argument for `dired-do-create-files'.")
1688
1689 ;;;###autoload
1690 (defun dired-do-copy (&optional arg)
1691 "Copy all marked (or next ARG) files, or copy the current file.
1692 This normally preserves the last-modified date when copying.
1693 When operating on just the current file, you specify the new name.
1694 When operating on multiple or marked files, you specify a directory,
1695 and new copies of these files are made in that directory
1696 with the same names that the files currently have. The default
1697 suggested for the target directory depends on the value of
1698 `dired-dwim-target', which see.
1699
1700 This command copies symbolic links by creating new ones,
1701 like `cp -d'."
1702 (interactive "P")
1703 (let ((dired-recursive-copies dired-recursive-copies))
1704 (dired-do-create-files 'copy (function dired-copy-file)
1705 "Copy"
1706 arg dired-keep-marker-copy
1707 nil dired-copy-how-to-fn)))
1708
1709 ;;;###autoload
1710 (defun dired-do-symlink (&optional arg)
1711 "Make symbolic links to current file or all marked (or next ARG) files.
1712 When operating on just the current file, you specify the new name.
1713 When operating on multiple or marked files, you specify a directory
1714 and new symbolic links are made in that directory
1715 with the same names that the files currently have. The default
1716 suggested for the target directory depends on the value of
1717 `dired-dwim-target', which see.
1718
1719 For relative symlinks, use \\[dired-do-relsymlink]."
1720 (interactive "P")
1721 (dired-do-create-files 'symlink (function make-symbolic-link)
1722 "Symlink" arg dired-keep-marker-symlink))
1723
1724 ;;;###autoload
1725 (defun dired-do-hardlink (&optional arg)
1726 "Add names (hard links) current file or all marked (or next ARG) files.
1727 When operating on just the current file, you specify the new name.
1728 When operating on multiple or marked files, you specify a directory
1729 and new hard links are made in that directory
1730 with the same names that the files currently have. The default
1731 suggested for the target directory depends on the value of
1732 `dired-dwim-target', which see."
1733 (interactive "P")
1734 (dired-do-create-files 'hardlink (function dired-hardlink)
1735 "Hardlink" arg dired-keep-marker-hardlink))
1736
1737 (defun dired-hardlink (file newname &optional ok-if-already-exists)
1738 (dired-handle-overwrite newname)
1739 ;; error is caught in -create-files
1740 (add-name-to-file file newname ok-if-already-exists)
1741 ;; Update the link count
1742 (dired-relist-file file))
1743
1744 ;;;###autoload
1745 (defun dired-do-rename (&optional arg)
1746 "Rename current file or all marked (or next ARG) files.
1747 When renaming just the current file, you specify the new name.
1748 When renaming multiple or marked files, you specify a directory.
1749 This command also renames any buffers that are visiting the files.
1750 The default suggested for the target directory depends on the value
1751 of `dired-dwim-target', which see."
1752 (interactive "P")
1753 (dired-do-create-files 'move (function dired-rename-file)
1754 "Move" arg dired-keep-marker-rename "Rename"))
1755 ;;;###end dired-cp.el
1756 \f
1757 ;;; 5K
1758 ;;;###begin dired-re.el
1759 (defvar rename-regexp-query)
1760
1761 (defun dired-do-create-files-regexp
1762 (file-creator operation arg regexp newname &optional whole-name marker-char)
1763 ;; Create a new file for each marked file using regexps.
1764 ;; FILE-CREATOR and OPERATION as in dired-create-files.
1765 ;; ARG as in dired-get-marked-files.
1766 ;; Matches each marked file against REGEXP and constructs the new
1767 ;; filename from NEWNAME (like in function replace-match).
1768 ;; Optional arg WHOLE-NAME means match/replace the whole file name
1769 ;; instead of only the non-directory part of the file.
1770 ;; Optional arg MARKER-CHAR as in dired-create-files.
1771 (let* ((fn-list (dired-get-marked-files nil arg))
1772 (operation-prompt (concat operation " `%s' to `%s'?"))
1773 (rename-regexp-help-form (format "\
1774 Type SPC or `y' to %s one match, DEL or `n' to skip to next,
1775 `!' to %s all remaining matches with no more questions."
1776 (downcase operation)
1777 (downcase operation)))
1778 (regexp-name-constructor
1779 ;; Function to construct new filename using REGEXP and NEWNAME:
1780 (if whole-name ; easy (but rare) case
1781 (function
1782 (lambda (from)
1783 (let ((to (dired-string-replace-match regexp from newname))
1784 ;; must bind help-form directly around call to
1785 ;; dired-query
1786 (help-form rename-regexp-help-form))
1787 (if to
1788 (and (dired-query 'rename-regexp-query
1789 operation-prompt
1790 from
1791 to)
1792 to)
1793 (dired-log "%s: %s did not match regexp %s\n"
1794 operation from regexp)))))
1795 ;; not whole-name, replace non-directory part only
1796 (function
1797 (lambda (from)
1798 (let* ((new (dired-string-replace-match
1799 regexp (file-name-nondirectory from) newname))
1800 (to (and new ; nil means there was no match
1801 (expand-file-name new
1802 (file-name-directory from))))
1803 (help-form rename-regexp-help-form))
1804 (if to
1805 (and (dired-query 'rename-regexp-query
1806 operation-prompt
1807 (dired-make-relative from)
1808 (dired-make-relative to))
1809 to)
1810 (dired-log "%s: %s did not match regexp %s\n"
1811 operation (file-name-nondirectory from) regexp)))))))
1812 rename-regexp-query)
1813 (dired-create-files
1814 file-creator operation fn-list regexp-name-constructor marker-char)))
1815
1816 (defun dired-mark-read-regexp (operation)
1817 ;; Prompt user about performing OPERATION.
1818 ;; Read and return list of: regexp newname arg whole-name.
1819 (let* ((whole-name
1820 (equal 0 (prefix-numeric-value current-prefix-arg)))
1821 (arg
1822 (if whole-name nil current-prefix-arg))
1823 (regexp
1824 (dired-read-regexp
1825 (concat (if whole-name "Abs. " "") operation " from (regexp): ")))
1826 (newname
1827 (read-string
1828 (concat (if whole-name "Abs. " "") operation " " regexp " to: "))))
1829 (list regexp newname arg whole-name)))
1830
1831 ;;;###autoload
1832 (defun dired-do-rename-regexp (regexp newname &optional arg whole-name)
1833 "Rename selected files whose names match REGEXP to NEWNAME.
1834
1835 With non-zero prefix argument ARG, the command operates on the next ARG
1836 files. Otherwise, it operates on all the marked files, or the current
1837 file if none are marked.
1838
1839 As each match is found, the user must type a character saying
1840 what to do with it. For directions, type \\[help-command] at that time.
1841 NEWNAME may contain \\=\\<n> or \\& as in `query-replace-regexp'.
1842 REGEXP defaults to the last regexp used.
1843
1844 With a zero prefix arg, renaming by regexp affects the absolute file name.
1845 Normally, only the non-directory part of the file name is used and changed."
1846 (interactive (dired-mark-read-regexp "Rename"))
1847 (dired-do-create-files-regexp
1848 (function dired-rename-file)
1849 "Rename" arg regexp newname whole-name dired-keep-marker-rename))
1850
1851 ;;;###autoload
1852 (defun dired-do-copy-regexp (regexp newname &optional arg whole-name)
1853 "Copy selected files whose names match REGEXP to NEWNAME.
1854 See function `dired-do-rename-regexp' for more info."
1855 (interactive (dired-mark-read-regexp "Copy"))
1856 (let ((dired-recursive-copies nil)) ; No recursive copies.
1857 (dired-do-create-files-regexp
1858 (function dired-copy-file)
1859 (if dired-copy-preserve-time "Copy [-p]" "Copy")
1860 arg regexp newname whole-name dired-keep-marker-copy)))
1861
1862 ;;;###autoload
1863 (defun dired-do-hardlink-regexp (regexp newname &optional arg whole-name)
1864 "Hardlink selected files whose names match REGEXP to NEWNAME.
1865 See function `dired-do-rename-regexp' for more info."
1866 (interactive (dired-mark-read-regexp "HardLink"))
1867 (dired-do-create-files-regexp
1868 (function add-name-to-file)
1869 "HardLink" arg regexp newname whole-name dired-keep-marker-hardlink))
1870
1871 ;;;###autoload
1872 (defun dired-do-symlink-regexp (regexp newname &optional arg whole-name)
1873 "Symlink selected files whose names match REGEXP to NEWNAME.
1874 See function `dired-do-rename-regexp' for more info."
1875 (interactive (dired-mark-read-regexp "SymLink"))
1876 (dired-do-create-files-regexp
1877 (function make-symbolic-link)
1878 "SymLink" arg regexp newname whole-name dired-keep-marker-symlink))
1879
1880 (defvar rename-non-directory-query)
1881
1882 (defun dired-create-files-non-directory
1883 (file-creator basename-constructor operation arg)
1884 ;; Perform FILE-CREATOR on the non-directory part of marked files
1885 ;; using function BASENAME-CONSTRUCTOR, with query for each file.
1886 ;; OPERATION like in dired-create-files, ARG as in dired-get-marked-files.
1887 (let (rename-non-directory-query)
1888 (dired-create-files
1889 file-creator
1890 operation
1891 (dired-get-marked-files nil arg)
1892 (function
1893 (lambda (from)
1894 (let ((to (concat (file-name-directory from)
1895 (funcall basename-constructor
1896 (file-name-nondirectory from)))))
1897 (and (let ((help-form (format "\
1898 Type SPC or `y' to %s one file, DEL or `n' to skip to next,
1899 `!' to %s all remaining matches with no more questions."
1900 (downcase operation)
1901 (downcase operation))))
1902 (dired-query 'rename-non-directory-query
1903 (concat operation " `%s' to `%s'")
1904 (dired-make-relative from)
1905 (dired-make-relative to)))
1906 to))))
1907 dired-keep-marker-rename)))
1908
1909 (defun dired-rename-non-directory (basename-constructor operation arg)
1910 (dired-create-files-non-directory
1911 (function dired-rename-file)
1912 basename-constructor operation arg))
1913
1914 ;;;###autoload
1915 (defun dired-upcase (&optional arg)
1916 "Rename all marked (or next ARG) files to upper case."
1917 (interactive "P")
1918 (dired-rename-non-directory (function upcase) "Rename upcase" arg))
1919
1920 ;;;###autoload
1921 (defun dired-downcase (&optional arg)
1922 "Rename all marked (or next ARG) files to lower case."
1923 (interactive "P")
1924 (dired-rename-non-directory (function downcase) "Rename downcase" arg))
1925
1926 ;;;###end dired-re.el
1927 \f
1928 ;;; 13K
1929 ;;;###begin dired-ins.el
1930
1931 ;;;###autoload
1932 (defun dired-maybe-insert-subdir (dirname &optional
1933 switches no-error-if-not-dir-p)
1934 "Insert this subdirectory into the same dired buffer.
1935 If it is already present, just move to it (type \\[dired-do-redisplay] to refresh),
1936 else inserts it at its natural place (as `ls -lR' would have done).
1937 With a prefix arg, you may edit the ls switches used for this listing.
1938 You can add `R' to the switches to expand the whole tree starting at
1939 this subdirectory.
1940 This function takes some pains to conform to `ls -lR' output.
1941
1942 Dired remembers switches specified with a prefix arg, so that reverting
1943 the buffer will not reset them. However, using `dired-undo' to re-insert
1944 or delete subdirectories can bypass this machinery. Hence, you sometimes
1945 may have to reset some subdirectory switches after a `dired-undo'.
1946 You can reset all subdirectory switches to the default using
1947 \\<dired-mode-map>\\[dired-reset-subdir-switches].
1948 See Info node `(emacs)Subdir switches' for more details."
1949 (interactive
1950 (list (dired-get-filename)
1951 (if current-prefix-arg
1952 (read-string "Switches for listing: "
1953 (or dired-subdir-switches dired-actual-switches)))))
1954 (let ((opoint (point)))
1955 ;; We don't need a marker for opoint as the subdir is always
1956 ;; inserted *after* opoint.
1957 (setq dirname (file-name-as-directory dirname))
1958 (or (and (not switches)
1959 (dired-goto-subdir dirname))
1960 (dired-insert-subdir dirname switches no-error-if-not-dir-p))
1961 ;; Push mark so that it's easy to find back. Do this after the
1962 ;; insert message so that the user sees the `Mark set' message.
1963 (push-mark opoint)))
1964
1965 ;;;###autoload
1966 (defun dired-insert-subdir (dirname &optional switches no-error-if-not-dir-p)
1967 "Insert this subdirectory into the same dired buffer.
1968 If it is already present, overwrites previous entry,
1969 else inserts it at its natural place (as `ls -lR' would have done).
1970 With a prefix arg, you may edit the `ls' switches used for this listing.
1971 You can add `R' to the switches to expand the whole tree starting at
1972 this subdirectory.
1973 This function takes some pains to conform to `ls -lR' output."
1974 ;; NO-ERROR-IF-NOT-DIR-P needed for special filesystems like
1975 ;; Prospero where dired-ls does the right thing, but
1976 ;; file-directory-p has not been redefined.
1977 (interactive
1978 (list (dired-get-filename)
1979 (if current-prefix-arg
1980 (read-string "Switches for listing: "
1981 (or dired-subdir-switches dired-actual-switches)))))
1982 (setq dirname (file-name-as-directory (expand-file-name dirname)))
1983 (or no-error-if-not-dir-p
1984 (file-directory-p dirname)
1985 (error "Attempt to insert a non-directory: %s" dirname))
1986 (let ((elt (assoc dirname dired-subdir-alist))
1987 (cons (assoc-string dirname dired-switches-alist))
1988 (modflag (buffer-modified-p))
1989 (old-switches switches)
1990 switches-have-R mark-alist case-fold-search buffer-read-only)
1991 (and (not switches) cons (setq switches (cdr cons)))
1992 (dired-insert-subdir-validate dirname switches)
1993 ;; case-fold-search is nil now, so we can test for capital `R':
1994 (if (setq switches-have-R (and switches (string-match "R" switches)))
1995 ;; avoid duplicated subdirs
1996 (setq mark-alist (dired-kill-tree dirname t)))
1997 (if elt
1998 ;; If subdir is already present, remove it and remember its marks
1999 (setq mark-alist (nconc (dired-insert-subdir-del elt) mark-alist))
2000 (dired-insert-subdir-newpos dirname)) ; else compute new position
2001 (dired-insert-subdir-doupdate
2002 dirname elt (dired-insert-subdir-doinsert dirname switches))
2003 (when old-switches
2004 (if cons
2005 (setcdr cons switches)
2006 (push (cons dirname switches) dired-switches-alist)))
2007 (when switches-have-R
2008 (dired-build-subdir-alist switches)
2009 (setq switches (dired-replace-in-string "R" "" switches))
2010 (dolist (cur-ass dired-subdir-alist)
2011 (let ((cur-dir (car cur-ass)))
2012 (and (dired-in-this-tree cur-dir dirname)
2013 (let ((cur-cons (assoc-string cur-dir dired-switches-alist)))
2014 (if cur-cons
2015 (setcdr cur-cons switches)
2016 (push (cons cur-dir switches) dired-switches-alist)))))))
2017 (dired-initial-position dirname)
2018 (save-excursion (dired-mark-remembered mark-alist))
2019 (restore-buffer-modified-p modflag)))
2020
2021 (defun dired-insert-subdir-validate (dirname &optional switches)
2022 ;; Check that it is valid to insert DIRNAME with SWITCHES.
2023 ;; Signal an error if invalid (e.g. user typed `i' on `..').
2024 (or (dired-in-this-tree dirname (expand-file-name default-directory))
2025 (error "%s: not in this directory tree" dirname))
2026 (let ((real-switches (or switches dired-subdir-switches)))
2027 (when real-switches
2028 (let (case-fold-search)
2029 (mapcar
2030 (function
2031 (lambda (x)
2032 (or (eq (null (string-match x real-switches))
2033 (null (string-match x dired-actual-switches)))
2034 (error
2035 "Can't have dirs with and without -%s switches together" x))))
2036 ;; all switches that make a difference to dired-get-filename:
2037 '("F" "b"))))))
2038
2039 (defun dired-alist-add (dir new-marker)
2040 ;; Add new DIR at NEW-MARKER. Sort alist.
2041 (dired-alist-add-1 dir new-marker)
2042 (dired-alist-sort))
2043
2044 (defun dired-alist-sort ()
2045 ;; Keep the alist sorted on buffer position.
2046 (setq dired-subdir-alist
2047 (sort dired-subdir-alist
2048 (function (lambda (elt1 elt2)
2049 (> (dired-get-subdir-min elt1)
2050 (dired-get-subdir-min elt2)))))))
2051
2052 (defun dired-kill-tree (dirname &optional remember-marks kill-root)
2053 "Kill all proper subdirs of DIRNAME, excluding DIRNAME itself.
2054 Interactively, you can kill DIRNAME as well by using a prefix argument.
2055 In interactive use, the command prompts for DIRNAME.
2056
2057 When called from Lisp, if REMEMBER-MARKS is non-nil, return an alist
2058 of marked files. If KILL-ROOT is non-nil, kill DIRNAME as well."
2059 (interactive "DKill tree below directory: \ni\nP")
2060 (setq dirname (file-name-as-directory (expand-file-name dirname)))
2061 (let ((s-alist dired-subdir-alist) dir m-alist)
2062 (while s-alist
2063 (setq dir (car (car s-alist))
2064 s-alist (cdr s-alist))
2065 (and (or kill-root (not (string-equal dir dirname)))
2066 (dired-in-this-tree dir dirname)
2067 (dired-goto-subdir dir)
2068 (setq m-alist (nconc (dired-kill-subdir remember-marks) m-alist))))
2069 m-alist))
2070
2071 (defun dired-insert-subdir-newpos (new-dir)
2072 ;; Find pos for new subdir, according to tree order.
2073 ;;(goto-char (point-max))
2074 (let ((alist dired-subdir-alist) elt dir pos new-pos)
2075 (while alist
2076 (setq elt (car alist)
2077 alist (cdr alist)
2078 dir (car elt))
2079 (if (dired-tree-lessp dir new-dir)
2080 ;; Insert NEW-DIR after DIR
2081 (setq new-pos (dired-get-subdir-max elt)
2082 alist nil)))
2083 (goto-char new-pos))
2084 ;; want a separating newline between subdirs
2085 (or (eobp)
2086 (forward-line -1))
2087 (insert "\n")
2088 (point))
2089
2090 (defun dired-insert-subdir-del (element)
2091 ;; Erase an already present subdir (given by ELEMENT) from buffer.
2092 ;; Move to that buffer position. Return a mark-alist.
2093 (let ((begin-marker (dired-get-subdir-min element)))
2094 (goto-char begin-marker)
2095 ;; Are at beginning of subdir (and inside it!). Now determine its end:
2096 (goto-char (dired-subdir-max))
2097 (or (eobp);; want a separating newline _between_ subdirs:
2098 (forward-char -1))
2099 (prog1
2100 (dired-remember-marks begin-marker (point))
2101 (delete-region begin-marker (point)))))
2102
2103 (defun dired-insert-subdir-doinsert (dirname switches)
2104 ;; Insert ls output after point.
2105 ;; Return the boundary of the inserted text (as list of BEG and END).
2106 (save-excursion
2107 (let ((begin (point)))
2108 (let ((dired-actual-switches
2109 (or switches
2110 dired-subdir-switches
2111 (dired-replace-in-string "R" "" dired-actual-switches))))
2112 (if (equal dirname (car (car (last dired-subdir-alist))))
2113 ;; If doing the top level directory of the buffer,
2114 ;; redo it as specified in dired-directory.
2115 (dired-readin-insert)
2116 (dired-insert-directory dirname dired-actual-switches nil nil t)))
2117 (list begin (point)))))
2118
2119 (defun dired-insert-subdir-doupdate (dirname elt beg-end)
2120 ;; Point is at the correct subdir alist position for ELT,
2121 ;; BEG-END is the subdir-region (as list of begin and end).
2122 (if elt ; subdir was already present
2123 ;; update its position (should actually be unchanged)
2124 (set-marker (dired-get-subdir-min elt) (point-marker))
2125 (dired-alist-add dirname (point-marker)))
2126 ;; The hook may depend on the subdir-alist containing the just
2127 ;; inserted subdir, so run it after dired-alist-add:
2128 (if dired-after-readin-hook
2129 (save-excursion
2130 (let ((begin (nth 0 beg-end))
2131 (end (nth 1 beg-end)))
2132 (goto-char begin)
2133 (save-restriction
2134 (narrow-to-region begin end)
2135 ;; hook may add or delete lines, but the subdir boundary
2136 ;; marker floats
2137 (run-hooks 'dired-after-readin-hook))))))
2138
2139 (defun dired-tree-lessp (dir1 dir2)
2140 ;; Lexicographic order on file name components, like `ls -lR':
2141 ;; DIR1 < DIR2 if DIR1 comes *before* DIR2 in an `ls -lR' listing,
2142 ;; i.e., if DIR1 is a (grand)parent dir of DIR2,
2143 ;; or DIR1 and DIR2 are in the same parentdir and their last
2144 ;; components are string-lessp.
2145 ;; Thus ("/usr/" "/usr/bin") and ("/usr/a/" "/usr/b/") are tree-lessp.
2146 ;; string-lessp could arguably be replaced by file-newer-than-file-p
2147 ;; if dired-actual-switches contained `t'.
2148 (setq dir1 (file-name-as-directory dir1)
2149 dir2 (file-name-as-directory dir2))
2150 (let ((components-1 (dired-split "/" dir1))
2151 (components-2 (dired-split "/" dir2)))
2152 (while (and components-1
2153 components-2
2154 (equal (car components-1) (car components-2)))
2155 (setq components-1 (cdr components-1)
2156 components-2 (cdr components-2)))
2157 (let ((c1 (car components-1))
2158 (c2 (car components-2)))
2159
2160 (cond ((and c1 c2)
2161 (string-lessp c1 c2))
2162 ((and (null c1) (null c2))
2163 nil) ; they are equal, not lessp
2164 ((null c1) ; c2 is a subdir of c1: c1<c2
2165 t)
2166 ((null c2) ; c1 is a subdir of c2: c1>c2
2167 nil)
2168 (t (error "This can't happen"))))))
2169
2170 ;; There should be a builtin split function - inverse to mapconcat.
2171 (defun dired-split (pat str &optional limit)
2172 "Splitting on regexp PAT, turn string STR into a list of substrings.
2173 Optional third arg LIMIT (>= 1) is a limit to the length of the
2174 resulting list.
2175 Thus, if SEP is a regexp that only matches itself,
2176
2177 (mapconcat 'identity (dired-split SEP STRING) SEP)
2178
2179 is always equal to STRING."
2180 (let* ((start (string-match pat str))
2181 (result (list (substring str 0 start)))
2182 (count 1)
2183 (end (if start (match-end 0))))
2184 (if end ; else nothing left
2185 (while (and (or (not (integerp limit))
2186 (< count limit))
2187 (string-match pat str end))
2188 (setq start (match-beginning 0)
2189 count (1+ count)
2190 result (cons (substring str end start) result)
2191 end (match-end 0)
2192 start end)
2193 ))
2194 (if (and (or (not (integerp limit))
2195 (< count limit))
2196 end) ; else nothing left
2197 (setq result
2198 (cons (substring str end) result)))
2199 (nreverse result)))
2200 \f
2201 ;;; moving by subdirectories
2202
2203 ;;;###autoload
2204 (defun dired-prev-subdir (arg &optional no-error-if-not-found no-skip)
2205 "Go to previous subdirectory, regardless of level.
2206 When called interactively and not on a subdir line, go to this subdir's line."
2207 ;;(interactive "p")
2208 (interactive
2209 (list (if current-prefix-arg
2210 (prefix-numeric-value current-prefix-arg)
2211 ;; if on subdir start already, don't stay there!
2212 (if (dired-get-subdir) 1 0))))
2213 (dired-next-subdir (- arg) no-error-if-not-found no-skip))
2214
2215 (defun dired-subdir-min ()
2216 (save-excursion
2217 (if (not (dired-prev-subdir 0 t t))
2218 (error "Not in a subdir!")
2219 (point))))
2220
2221 ;;;###autoload
2222 (defun dired-goto-subdir (dir)
2223 "Go to end of header line of DIR in this dired buffer.
2224 Return value of point on success, otherwise return nil.
2225 The next char is either \\n, or \\r if DIR is hidden."
2226 (interactive
2227 (prog1 ; let push-mark display its message
2228 (list (expand-file-name
2229 (completing-read "Goto in situ directory: " ; prompt
2230 dired-subdir-alist ; table
2231 nil ; predicate
2232 t ; require-match
2233 (dired-current-directory))))
2234 (push-mark)))
2235 (setq dir (file-name-as-directory dir))
2236 (let ((elt (assoc dir dired-subdir-alist)))
2237 (and elt
2238 (goto-char (dired-get-subdir-min elt))
2239 ;; dired-subdir-hidden-p and dired-add-entry depend on point being
2240 ;; at either \r or \n after this function succeeds.
2241 (progn (skip-chars-forward "^\r\n")
2242 (point)))))
2243 \f
2244 ;;;###autoload
2245 (defun dired-mark-subdir-files ()
2246 "Mark all files except `.' and `..' in current subdirectory.
2247 If the Dired buffer shows multiple directories, this command
2248 marks the files listed in the subdirectory that point is in."
2249 (interactive)
2250 (let ((p-min (dired-subdir-min)))
2251 (dired-mark-files-in-region p-min (dired-subdir-max))))
2252
2253 ;;;###autoload
2254 (defun dired-kill-subdir (&optional remember-marks)
2255 "Remove all lines of current subdirectory.
2256 Lower levels are unaffected."
2257 ;; With optional REMEMBER-MARKS, return a mark-alist.
2258 (interactive)
2259 (let* ((beg (dired-subdir-min))
2260 (end (dired-subdir-max))
2261 (modflag (buffer-modified-p))
2262 (cur-dir (dired-current-directory))
2263 (cons (assoc-string cur-dir dired-switches-alist))
2264 buffer-read-only)
2265 (if (equal cur-dir default-directory)
2266 (error "Attempt to kill top level directory"))
2267 (prog1
2268 (if remember-marks (dired-remember-marks beg end))
2269 (delete-region beg end)
2270 (if (eobp) ; don't leave final blank line
2271 (delete-char -1))
2272 (dired-unsubdir cur-dir)
2273 (when cons
2274 (setq dired-switches-alist (delete cons dired-switches-alist)))
2275 (restore-buffer-modified-p modflag))))
2276
2277 (defun dired-unsubdir (dir)
2278 ;; Remove DIR from the alist
2279 (setq dired-subdir-alist
2280 (delq (assoc dir dired-subdir-alist) dired-subdir-alist)))
2281
2282 ;;;###autoload
2283 (defun dired-tree-up (arg)
2284 "Go up ARG levels in the dired tree."
2285 (interactive "p")
2286 (let ((dir (dired-current-directory)))
2287 (while (>= arg 1)
2288 (setq arg (1- arg)
2289 dir (file-name-directory (directory-file-name dir))))
2290 ;;(setq dir (expand-file-name dir))
2291 (or (dired-goto-subdir dir)
2292 (error "Cannot go up to %s - not in this tree" dir))))
2293
2294 ;;;###autoload
2295 (defun dired-tree-down ()
2296 "Go down in the dired tree."
2297 (interactive)
2298 (let ((dir (dired-current-directory)) ; has slash
2299 pos case-fold-search) ; filenames are case sensitive
2300 (let ((rest (reverse dired-subdir-alist)) elt)
2301 (while rest
2302 (setq elt (car rest)
2303 rest (cdr rest))
2304 (if (dired-in-this-tree (directory-file-name (car elt)) dir)
2305 (setq rest nil
2306 pos (dired-goto-subdir (car elt))))))
2307 (if pos
2308 (goto-char pos)
2309 (error "At the bottom"))))
2310 \f
2311 ;;; hiding
2312
2313 (defun dired-unhide-subdir ()
2314 (let (buffer-read-only)
2315 (subst-char-in-region (dired-subdir-min) (dired-subdir-max) ?\r ?\n)))
2316
2317 (defun dired-hide-check ()
2318 (or selective-display
2319 (error "selective-display must be t for subdir hiding to work!")))
2320
2321 (defun dired-subdir-hidden-p (dir)
2322 (and selective-display
2323 (save-excursion
2324 (dired-goto-subdir dir)
2325 (looking-at "\r"))))
2326
2327 ;;;###autoload
2328 (defun dired-hide-subdir (arg)
2329 "Hide or unhide the current subdirectory and move to next directory.
2330 Optional prefix arg is a repeat factor.
2331 Use \\[dired-hide-all] to (un)hide all directories."
2332 (interactive "p")
2333 (dired-hide-check)
2334 (let ((modflag (buffer-modified-p)))
2335 (while (>= (setq arg (1- arg)) 0)
2336 (let* ((cur-dir (dired-current-directory))
2337 (hidden-p (dired-subdir-hidden-p cur-dir))
2338 (elt (assoc cur-dir dired-subdir-alist))
2339 (end-pos (1- (dired-get-subdir-max elt)))
2340 buffer-read-only)
2341 ;; keep header line visible, hide rest
2342 (goto-char (dired-get-subdir-min elt))
2343 (skip-chars-forward "^\n\r")
2344 (if hidden-p
2345 (subst-char-in-region (point) end-pos ?\r ?\n)
2346 (subst-char-in-region (point) end-pos ?\n ?\r)))
2347 (dired-next-subdir 1 t))
2348 (restore-buffer-modified-p modflag)))
2349
2350 ;;;###autoload
2351 (defun dired-hide-all (&optional ignored)
2352 "Hide all subdirectories, leaving only their header lines.
2353 If there is already something hidden, make everything visible again.
2354 Use \\[dired-hide-subdir] to (un)hide a particular subdirectory."
2355 (interactive "P")
2356 (dired-hide-check)
2357 (let ((modflag (buffer-modified-p))
2358 buffer-read-only)
2359 (if (save-excursion
2360 (goto-char (point-min))
2361 (search-forward "\r" nil t))
2362 ;; unhide - bombs on \r in filenames
2363 (subst-char-in-region (point-min) (point-max) ?\r ?\n)
2364 ;; hide
2365 (let ((pos (point-max)) ; pos of end of last directory
2366 (alist dired-subdir-alist))
2367 (while alist ; while there are dirs before pos
2368 (subst-char-in-region (dired-get-subdir-min (car alist)) ; pos of prev dir
2369 (save-excursion
2370 (goto-char pos) ; current dir
2371 ;; we're somewhere on current dir's line
2372 (forward-line -1)
2373 (point))
2374 ?\n ?\r)
2375 (setq pos (dired-get-subdir-min (car alist))) ; prev dir gets current dir
2376 (setq alist (cdr alist)))))
2377 (restore-buffer-modified-p modflag)))
2378
2379 ;;;###end dired-ins.el
2380
2381 \f
2382 ;; Search only in file names in the Dired buffer.
2383
2384 (defcustom dired-isearch-filenames nil
2385 "Non-nil to Isearch in file names only.
2386 If t, Isearch in Dired always matches only file names.
2387 If `dwim', Isearch matches file names when initial point position is on
2388 a file name. Otherwise, it searches the whole buffer without restrictions."
2389 :type '(choice (const :tag "No restrictions" nil)
2390 (const :tag "When point is on a file name initially, search file names" dwim)
2391 (const :tag "Always search in file names" t))
2392 :group 'dired
2393 :version "23.1")
2394
2395 (defvar dired-isearch-filter-predicate-orig nil)
2396
2397 (defun dired-isearch-filenames-toggle ()
2398 "Toggle file names searching on or off.
2399 When on, Isearch skips matches outside file names using the predicate
2400 `dired-isearch-filter-filenames' that matches only at file names.
2401 When off, it uses the original predicate."
2402 (interactive)
2403 (setq isearch-filter-predicate
2404 (if (eq isearch-filter-predicate 'dired-isearch-filter-filenames)
2405 dired-isearch-filter-predicate-orig
2406 'dired-isearch-filter-filenames))
2407 (setq isearch-success t isearch-adjusted t)
2408 (isearch-update))
2409
2410 ;;;###autoload
2411 (defun dired-isearch-filenames-setup ()
2412 "Set up isearch to search in Dired file names.
2413 Intended to be added to `isearch-mode-hook'."
2414 (when (or (eq dired-isearch-filenames t)
2415 (and (eq dired-isearch-filenames 'dwim)
2416 (get-text-property (point) 'dired-filename)))
2417 (setq isearch-message-prefix-add "filename ")
2418 (define-key isearch-mode-map "\M-sf" 'dired-isearch-filenames-toggle)
2419 (setq dired-isearch-filter-predicate-orig
2420 (default-value 'isearch-filter-predicate))
2421 (setq-default isearch-filter-predicate 'dired-isearch-filter-filenames)
2422 (add-hook 'isearch-mode-end-hook 'dired-isearch-filenames-end nil t)))
2423
2424 (defun dired-isearch-filenames-end ()
2425 "Clean up the Dired file name search after terminating isearch."
2426 (setq isearch-message-prefix-add nil)
2427 (define-key isearch-mode-map "\M-sf" nil)
2428 (setq-default isearch-filter-predicate dired-isearch-filter-predicate-orig)
2429 (remove-hook 'isearch-mode-end-hook 'dired-isearch-filenames-end t))
2430
2431 (defun dired-isearch-filter-filenames (beg end)
2432 "Test whether the current search hit is a visible file name.
2433 Return non-nil if the text from BEG to END is part of a file
2434 name (has the text property `dired-filename') and is visible."
2435 (and (isearch-filter-visible beg end)
2436 (if dired-isearch-filenames
2437 (text-property-not-all (min beg end) (max beg end)
2438 'dired-filename nil)
2439 t)))
2440
2441 ;;;###autoload
2442 (defun dired-isearch-filenames ()
2443 "Search for a string using Isearch only in file names in the Dired buffer."
2444 (interactive)
2445 (let ((dired-isearch-filenames t))
2446 (isearch-forward)))
2447
2448 ;;;###autoload
2449 (defun dired-isearch-filenames-regexp ()
2450 "Search for a regexp using Isearch only in file names in the Dired buffer."
2451 (interactive)
2452 (let ((dired-isearch-filenames t))
2453 (isearch-forward-regexp)))
2454
2455 \f
2456 ;; Functions for searching in tags style among marked files.
2457
2458 ;;;###autoload
2459 (defun dired-do-isearch ()
2460 "Search for a string through all marked files using Isearch."
2461 (interactive)
2462 (multi-isearch-files
2463 (dired-get-marked-files nil nil 'dired-nondirectory-p)))
2464
2465 ;;;###autoload
2466 (defun dired-do-isearch-regexp ()
2467 "Search for a regexp through all marked files using Isearch."
2468 (interactive)
2469 (multi-isearch-files-regexp
2470 (dired-get-marked-files nil nil 'dired-nondirectory-p)))
2471
2472 ;;;###autoload
2473 (defun dired-do-search (regexp)
2474 "Search through all marked files for a match for REGEXP.
2475 Stops when a match is found.
2476 To continue searching for next match, use command \\[tags-loop-continue]."
2477 (interactive "sSearch marked files (regexp): ")
2478 (tags-search regexp '(dired-get-marked-files nil nil 'dired-nondirectory-p)))
2479
2480 ;;;###autoload
2481 (defun dired-do-query-replace-regexp (from to &optional delimited)
2482 "Do `query-replace-regexp' of FROM with TO, on all marked files.
2483 Third arg DELIMITED (prefix arg) means replace only word-delimited matches.
2484 If you exit (\\[keyboard-quit], RET or q), you can resume the query replace
2485 with the command \\[tags-loop-continue]."
2486 (interactive
2487 (let ((common
2488 (query-replace-read-args
2489 "Query replace regexp in marked files" t t)))
2490 (list (nth 0 common) (nth 1 common) (nth 2 common))))
2491 (dolist (file (dired-get-marked-files nil nil 'dired-nondirectory-p))
2492 (let ((buffer (get-file-buffer file)))
2493 (if (and buffer (with-current-buffer buffer
2494 buffer-read-only))
2495 (error "File `%s' is visited read-only" file))))
2496 (tags-query-replace from to delimited
2497 '(dired-get-marked-files nil nil 'dired-nondirectory-p)))
2498
2499 (defun dired-nondirectory-p (file)
2500 (not (file-directory-p file)))
2501 \f
2502 ;;;###autoload
2503 (defun dired-show-file-type (file &optional deref-symlinks)
2504 "Print the type of FILE, according to the `file' command.
2505 If you give a prefix to this command, and FILE is a symbolic
2506 link, then the type of the file linked to by FILE is printed
2507 instead."
2508 (interactive (list (dired-get-filename t) current-prefix-arg))
2509 (let (process-file-side-effects)
2510 (with-temp-buffer
2511 (if deref-symlinks
2512 (process-file "file" nil t t "-L" "--" file)
2513 (process-file "file" nil t t "--" file))
2514 (when (bolp)
2515 (backward-delete-char 1))
2516 (message "%s" (buffer-string)))))
2517
2518 (provide 'dired-aux)
2519
2520 ;; Local Variables:
2521 ;; byte-compile-dynamic: t
2522 ;; generated-autoload-file: "dired.el"
2523 ;; End:
2524
2525 ;;; dired-aux.el ends here