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