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