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