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