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