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