]> code.delx.au - gnu-emacs/blob - lisp/dired-aux.el
Merge from origin/emacs-25
[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 (stuff-it
734 (if (or (string-match-p dired-star-subst-regexp command)
735 (string-match-p dired-quark-subst-regexp command))
736 (lambda (x)
737 (let ((retval command))
738 (while (string-match
739 "\\(^\\|[ \t]\\)\\([*?]\\)\\([ \t]\\|$\\)" retval)
740 (setq retval (replace-match x t t retval 2)))
741 retval))
742 (lambda (x) (concat command dired-mark-separator x)))))
743 (concat
744 (if on-each
745 (mapconcat stuff-it (mapcar 'shell-quote-argument file-list)
746 (if (and in-background (not sequentially)) "&" ";"))
747 (let ((files (mapconcat 'shell-quote-argument
748 file-list dired-mark-separator)))
749 (if (> (length file-list) 1)
750 (setq files (concat dired-mark-prefix files dired-mark-postfix)))
751 (funcall stuff-it files)))
752 (if in-background "&" ""))))
753
754 ;; This is an extra function so that it can be redefined by ange-ftp.
755 ;;;###autoload
756 (defun dired-run-shell-command (command)
757 (let ((handler
758 (find-file-name-handler (directory-file-name default-directory)
759 'shell-command)))
760 (if handler (apply handler 'shell-command (list command))
761 (shell-command command)))
762 ;; Return nil for sake of nconc in dired-bunch-files.
763 nil)
764 \f
765
766 (defun dired-check-process (msg program &rest arguments)
767 "Display MSG while running PROGRAM, and check for output.
768 Remaining arguments are strings passed as command arguments to PROGRAM.
769 On error, insert output
770 in a log buffer and return the offending ARGUMENTS or PROGRAM.
771 Caller can cons up a list of failed args.
772 Else returns nil for success."
773 (let (err-buffer err (dir default-directory))
774 (message "%s..." msg)
775 (save-excursion
776 ;; Get a clean buffer for error output:
777 (setq err-buffer (get-buffer-create " *dired-check-process output*"))
778 (set-buffer err-buffer)
779 (erase-buffer)
780 (setq default-directory dir ; caller's default-directory
781 err (not (eq 0 (apply 'process-file program nil t nil arguments))))
782 (if err
783 (progn
784 (dired-log (concat program " " (prin1-to-string arguments) "\n"))
785 (dired-log err-buffer)
786 (or arguments program t))
787 (kill-buffer err-buffer)
788 (message "%s...done" msg)
789 nil))))
790
791 (defun dired-shell-command (cmd)
792 "Run CMD, and check for output.
793 On error, pop up the log buffer.
794 Return the result of `process-file' - zero for success."
795 (let ((out-buffer " *dired-check-process output*")
796 (dir default-directory))
797 (with-current-buffer (get-buffer-create out-buffer)
798 (erase-buffer)
799 (let* ((default-directory dir)
800 (res (process-file
801 shell-file-name
802 nil
803 t
804 nil
805 shell-command-switch
806 cmd)))
807 (unless (zerop res)
808 (pop-to-buffer out-buffer))
809 res))))
810 \f
811 ;; Commands that delete or redisplay part of the dired buffer.
812
813 (defun dired-kill-line (&optional arg)
814 "Kill the current line (not the files).
815 With a prefix argument, kill that many lines starting with the current line.
816 \(A negative argument kills backward.)"
817 (interactive "P")
818 (setq arg (prefix-numeric-value arg))
819 (let (buffer-read-only file)
820 (while (/= 0 arg)
821 (setq file (dired-get-filename nil t))
822 (if (not file)
823 (error "Can only kill file lines")
824 (save-excursion (and file
825 (dired-goto-subdir file)
826 (dired-kill-subdir)))
827 (delete-region (line-beginning-position)
828 (progn (forward-line 1) (point)))
829 (if (> arg 0)
830 (setq arg (1- arg))
831 (setq arg (1+ arg))
832 (forward-line -1))))
833 (dired-move-to-filename)))
834
835 ;;;###autoload
836 (defun dired-do-kill-lines (&optional arg fmt)
837 "Kill all marked lines (not the files).
838 With a prefix argument, kill that many lines starting with the current line.
839 \(A negative argument kills backward.)
840 If you use this command with a prefix argument to kill the line
841 for a file that is a directory, which you have inserted in the
842 Dired buffer as a subdirectory, then it deletes that subdirectory
843 from the buffer as well.
844 To kill an entire subdirectory \(without killing its line in the
845 parent directory), go to its directory header line and use this
846 command with a prefix argument (the value does not matter)."
847 ;; Returns count of killed lines. FMT="" suppresses message.
848 (interactive "P")
849 (if arg
850 (if (dired-get-subdir)
851 (dired-kill-subdir)
852 (dired-kill-line arg))
853 (save-excursion
854 (goto-char (point-min))
855 (let (buffer-read-only
856 (count 0)
857 (regexp (dired-marker-regexp)))
858 (while (and (not (eobp))
859 (re-search-forward regexp nil t))
860 (setq count (1+ count))
861 (delete-region (line-beginning-position)
862 (progn (forward-line 1) (point))))
863 (or (equal "" fmt)
864 (message (or fmt "Killed %d line%s.") count (dired-plural-s count)))
865 count))))
866
867 ;;;###end dired-cmd.el
868 \f
869 ;;; 30K
870 ;;;###begin dired-cp.el
871
872 (defun dired-compress ()
873 ;; Compress or uncompress the current file.
874 ;; Return nil for success, offending filename else.
875 (let* (buffer-read-only
876 (from-file (dired-get-filename))
877 (new-file (dired-compress-file from-file)))
878 (if new-file
879 (let ((start (point)))
880 ;; Remove any preexisting entry for the name NEW-FILE.
881 (ignore-errors (dired-remove-entry new-file))
882 (goto-char start)
883 ;; Now replace the current line with an entry for NEW-FILE.
884 (dired-update-file-line new-file) nil)
885 (dired-log (concat "Failed to compress" from-file))
886 from-file)))
887
888 (defvar dired-compress-file-suffixes
889 '(
890 ;; "tar -zxf" isn't used because it's not available on the
891 ;; Solaris10 version of tar. Solaris10 becomes obsolete in 2021.
892 ;; Same thing on AIX 7.1.
893 ("\\.tar\\.gz\\'" "" "gzip -dc %i | tar -xv")
894 ("\\.gz\\'" "" "gunzip")
895 ("\\.tgz\\'" ".tar" "gunzip")
896 ("\\.Z\\'" "" "uncompress")
897 ;; For .z, try gunzip. It might be an old gzip file,
898 ;; or it might be from compact? pack? (which?) but gunzip handles both.
899 ("\\.z\\'" "" "gunzip")
900 ("\\.dz\\'" "" "dictunzip")
901 ("\\.tbz\\'" ".tar" "bunzip2")
902 ("\\.bz2\\'" "" "bunzip2")
903 ("\\.xz\\'" "" "unxz")
904 ("\\.zip\\'" "" "unzip -o -d %o %i")
905 ;; This item controls naming for compression.
906 ("\\.tar\\'" ".tgz" nil)
907 ;; This item controls the compression of directories
908 (":" ".tar.gz" "tar -c %i | gzip -c9 > %o"))
909 "Control changes in file name suffixes for compression and uncompression.
910 Each element specifies one transformation rule, and has the form:
911 (REGEXP NEW-SUFFIX PROGRAM)
912 The rule applies when the old file name matches REGEXP.
913 The new file name is computed by deleting the part that matches REGEXP
914 (as well as anything after that), then adding NEW-SUFFIX in its place.
915 If PROGRAM is non-nil, the rule is an uncompression rule,
916 and uncompression is done by running PROGRAM.
917
918 Within PROGRAM, %i denotes the input file, and %o denotes the
919 output file.
920
921 Otherwise, the rule is a compression rule, and compression is done with gzip.
922 ARGS are command switches passed to PROGRAM.")
923
924 (defvar dired-compress-files-alist
925 '(("\\.tar\\.gz\\'" . "tar -c %i | gzip -c9 > %o")
926 ("\\.tar\\.bz2\\'" . "tar -c %i | bzip2 -c9 > %o")
927 ("\\.tar\\.xz\\'" . "tar -c %i | xz -c9 > %o")
928 ("\\.zip\\'" . "zip %o -r --filesync %i"))
929 "Control the compression shell command for `dired-do-compress-to'.
930
931 Each element is (REGEXP . CMD), where REGEXP is the name of the
932 archive to which you want to compress, and CMD the the
933 corresponding command.
934
935 Within CMD, %i denotes the input file(s), and %o denotes the
936 output file. %i path(s) are relative, while %o is absolute.")
937
938 ;;;###autoload
939 (defun dired-do-compress-to ()
940 "Compress selected files and directories to an archive.
941 You are prompted for the archive name.
942 The archiving command is chosen based on the archive name extension and
943 `dired-compress-files-alist'."
944 (interactive)
945 (let* ((in-files (dired-get-marked-files))
946 (out-file (read-file-name "Compress to: "))
947 (rule (cl-find-if
948 (lambda (x)
949 (string-match (car x) out-file))
950 dired-compress-files-alist)))
951 (cond ((not rule)
952 (error
953 "No compression rule found for %s, see `dired-compress-files-alist'"
954 out-file))
955 ((and (file-exists-p out-file)
956 (not (y-or-n-p
957 (format "%s exists, overwrite?"
958 (abbreviate-file-name out-file)))))
959 (message "Compression aborted"))
960 (t
961 (when (zerop
962 (dired-shell-command
963 (replace-regexp-in-string
964 "%o" out-file
965 (replace-regexp-in-string
966 "%i" (mapconcat #'file-name-nondirectory in-files " ")
967 (cdr rule)))))
968 (message "Compressed %d file(s) to %s"
969 (length in-files)
970 (file-name-nondirectory out-file)))))))
971
972 ;;;###autoload
973 (defun dired-compress-file (file)
974 "Compress or uncompress FILE.
975 Return the name of the compressed or uncompressed file.
976 Return nil if no change in files."
977 (let ((handler (find-file-name-handler file 'dired-compress-file))
978 suffix newname
979 (suffixes dired-compress-file-suffixes)
980 command)
981 ;; See if any suffix rule matches this file name.
982 (while suffixes
983 (let (case-fold-search)
984 (if (string-match (car (car suffixes)) file)
985 (setq suffix (car suffixes) suffixes nil))
986 (setq suffixes (cdr suffixes))))
987 ;; If so, compute desired new name.
988 (if suffix
989 (setq newname (concat (substring file 0 (match-beginning 0))
990 (nth 1 suffix))))
991 (cond (handler
992 (funcall handler 'dired-compress-file file))
993 ((file-symlink-p file)
994 nil)
995 ((and suffix (setq command (nth 2 suffix)))
996 (if (string-match "%[io]" command)
997 (prog1 (setq newname (file-name-as-directory newname))
998 (dired-shell-command
999 (replace-regexp-in-string
1000 "%o" newname
1001 (replace-regexp-in-string
1002 "%i" file
1003 command))))
1004 ;; We found an uncompression rule.
1005 (when (not
1006 (dired-check-process
1007 (concat "Uncompressing " file)
1008 command
1009 file))
1010 newname)))
1011 (t
1012 ;; We don't recognize the file as compressed, so compress it.
1013 ;; Try gzip; if we don't have that, use compress.
1014 (condition-case nil
1015 (if (file-directory-p file)
1016 (progn
1017 (setq suffix (cdr (assoc ":" dired-compress-file-suffixes)))
1018 (when suffix
1019 (let ((out-name (concat file (car suffix)))
1020 (default-directory (file-name-directory file)))
1021 (dired-shell-command
1022 (replace-regexp-in-string
1023 "%o" out-name
1024 (replace-regexp-in-string
1025 "%i" (file-name-nondirectory file)
1026 (cadr suffix))))
1027 out-name)))
1028 (let ((out-name (concat file ".gz")))
1029 (and (or (not (file-exists-p out-name))
1030 (y-or-n-p
1031 (format "File %s already exists. Really compress? "
1032 out-name)))
1033 (not
1034 (dired-check-process (concat "Compressing " file)
1035 "gzip" "-f" file))
1036 (or (file-exists-p out-name)
1037 (setq out-name (concat file ".z")))
1038 ;; Rename the compressed file to NEWNAME
1039 ;; if it hasn't got that name already.
1040 (if (and newname (not (equal newname out-name)))
1041 (progn
1042 (rename-file out-name newname t)
1043 newname)
1044 out-name))))
1045 (file-error
1046 (if (not (dired-check-process (concat "Compressing " file)
1047 "compress" "-f" file))
1048 ;; Don't use NEWNAME with `compress'.
1049 (concat file ".Z"))))))))
1050 \f
1051 (defun dired-mark-confirm (op-symbol arg)
1052 ;; Request confirmation from the user that the operation described
1053 ;; by OP-SYMBOL is to be performed on the marked files.
1054 ;; Confirmation consists in a y-or-n question with a file list
1055 ;; pop-up unless OP-SYMBOL is a member of `dired-no-confirm'.
1056 ;; The files used are determined by ARG (as in dired-get-marked-files).
1057 (or (eq dired-no-confirm t)
1058 (memq op-symbol dired-no-confirm)
1059 ;; Pass t for DISTINGUISH-ONE-MARKED so that a single file which
1060 ;; is marked pops up a window. That will help the user see
1061 ;; it isn't the current line file.
1062 (let ((files (dired-get-marked-files t arg nil t))
1063 (string (if (eq op-symbol 'compress) "Compress or uncompress"
1064 (capitalize (symbol-name op-symbol)))))
1065 (dired-mark-pop-up nil op-symbol files (function y-or-n-p)
1066 (concat string " "
1067 (dired-mark-prompt arg files) "? ")))))
1068
1069 (defun dired-map-over-marks-check (fun arg op-symbol &optional show-progress)
1070 ; "Map FUN over marked files (with second ARG like in dired-map-over-marks)
1071 ; and display failures.
1072
1073 ; FUN takes zero args. It returns non-nil (the offending object, e.g.
1074 ; the short form of the filename) for a failure and probably logs a
1075 ; detailed error explanation using function `dired-log'.
1076
1077 ; OP-SYMBOL is a symbol describing the operation performed (e.g.
1078 ; `compress'). It is used with `dired-mark-pop-up' to prompt the user
1079 ; (e.g. with `Compress * [2 files]? ') and to display errors (e.g.
1080 ; `Failed to compress 1 of 2 files - type W to see why ("foo")')
1081
1082 ; SHOW-PROGRESS if non-nil means redisplay dired after each file."
1083 (if (dired-mark-confirm op-symbol arg)
1084 (let* ((total-list;; all of FUN's return values
1085 (dired-map-over-marks (funcall fun) arg show-progress))
1086 (total (length total-list))
1087 (failures (delq nil total-list))
1088 (count (length failures))
1089 (string (if (eq op-symbol 'compress) "Compress or uncompress"
1090 (capitalize (symbol-name op-symbol)))))
1091 (if (not failures)
1092 (message "%s: %d file%s."
1093 string total (dired-plural-s total))
1094 ;; end this bunch of errors:
1095 (dired-log-summary
1096 (format "Failed to %s %d of %d file%s"
1097 (downcase string) count total (dired-plural-s total))
1098 failures)))))
1099
1100 ;;;###autoload
1101 (defun dired-query (sym prompt &rest args)
1102 "Format PROMPT with ARGS, query user, and store the result in SYM.
1103 The return value is either nil or t.
1104
1105 The user may type y or SPC to accept once; n or DEL to skip once;
1106 ! to accept this and subsequent queries; or q or ESC to decline
1107 this and subsequent queries.
1108
1109 If SYM is already bound to a non-nil value, this function may
1110 return automatically without querying the user. If SYM is !,
1111 return t; if SYM is q or ESC, return nil."
1112 (let* ((char (symbol-value sym))
1113 (char-choices '(?y ?\s ?n ?\177 ?! ?q ?\e)))
1114 (cond ((eq char ?!)
1115 t) ; accept, and don't ask again
1116 ((memq char '(?q ?\e))
1117 nil) ; skip, and don't ask again
1118 (t ; no previous answer - ask now
1119 (setq prompt
1120 (concat (apply #'format-message prompt args)
1121 (if help-form
1122 (format " [Type yn!q or %s] "
1123 (key-description (vector help-char)))
1124 " [Type y, n, q or !] ")))
1125 (set sym (setq char (read-char-choice prompt char-choices)))
1126 (if (memq char '(?y ?\s ?!)) t)))))
1127
1128 \f
1129 ;;;###autoload
1130 (defun dired-do-compress (&optional arg)
1131 "Compress or uncompress marked (or next ARG) files."
1132 (interactive "P")
1133 (dired-map-over-marks-check (function dired-compress) arg 'compress t))
1134
1135 ;; Commands for Emacs Lisp files - load and byte compile
1136
1137 (defun dired-byte-compile ()
1138 ;; Return nil for success, offending file name else.
1139 (let* ((filename (dired-get-filename))
1140 elc-file buffer-read-only failure)
1141 (condition-case err
1142 (save-excursion (byte-compile-file filename))
1143 (error
1144 (setq failure err)))
1145 (setq elc-file (byte-compile-dest-file filename))
1146 (or (file-exists-p elc-file)
1147 (setq failure t))
1148 (if failure
1149 (progn
1150 (dired-log "Byte compile error for %s:\n%s\n" filename failure)
1151 (dired-make-relative filename))
1152 (dired-remove-file elc-file)
1153 (forward-line) ; insert .elc after its .el file
1154 (dired-add-file elc-file)
1155 nil)))
1156
1157 ;;;###autoload
1158 (defun dired-do-byte-compile (&optional arg)
1159 "Byte compile marked (or next ARG) Emacs Lisp files."
1160 (interactive "P")
1161 (dired-map-over-marks-check (function dired-byte-compile) arg 'byte-compile t))
1162
1163 (defun dired-load ()
1164 ;; Return nil for success, offending file name else.
1165 (let ((file (dired-get-filename)) failure)
1166 (condition-case err
1167 (load file nil nil t)
1168 (error (setq failure err)))
1169 (if (not failure)
1170 nil
1171 (dired-log "Load error for %s:\n%s\n" file failure)
1172 (dired-make-relative file))))
1173
1174 ;;;###autoload
1175 (defun dired-do-load (&optional arg)
1176 "Load the marked (or next ARG) Emacs Lisp files."
1177 (interactive "P")
1178 (dired-map-over-marks-check (function dired-load) arg 'load t))
1179
1180 ;;;###autoload
1181 (defun dired-do-redisplay (&optional arg test-for-subdir)
1182 "Redisplay all marked (or next ARG) files.
1183 If on a subdir line, redisplay that subdirectory. In that case,
1184 a prefix arg lets you edit the `ls' switches used for the new listing.
1185
1186 Dired remembers switches specified with a prefix arg, so that reverting
1187 the buffer will not reset them. However, using `dired-undo' to re-insert
1188 or delete subdirectories can bypass this machinery. Hence, you sometimes
1189 may have to reset some subdirectory switches after a `dired-undo'.
1190 You can reset all subdirectory switches to the default using
1191 \\<dired-mode-map>\\[dired-reset-subdir-switches].
1192 See Info node `(emacs)Subdir switches' for more details."
1193 ;; Moves point if the next ARG files are redisplayed.
1194 (interactive "P\np")
1195 (if (and test-for-subdir (dired-get-subdir))
1196 (let* ((dir (dired-get-subdir))
1197 (switches (cdr (assoc-string dir dired-switches-alist))))
1198 (dired-insert-subdir
1199 dir
1200 (when arg
1201 (read-string "Switches for listing: "
1202 (or switches
1203 dired-subdir-switches
1204 dired-actual-switches)))))
1205 (message "Redisplaying...")
1206 ;; message much faster than making dired-map-over-marks show progress
1207 (dired-uncache
1208 (if (consp dired-directory) (car dired-directory) dired-directory))
1209 (dired-map-over-marks (let ((fname (dired-get-filename))
1210 ;; Postpone readin hook till we map
1211 ;; over all marked files (Bug#6810).
1212 (dired-after-readin-hook nil))
1213 (message "Redisplaying... %s" fname)
1214 (dired-update-file-line fname))
1215 arg)
1216 (run-hooks 'dired-after-readin-hook)
1217 (dired-move-to-filename)
1218 (message "Redisplaying...done")))
1219
1220 (defun dired-reset-subdir-switches ()
1221 "Set `dired-switches-alist' to nil and revert dired buffer."
1222 (interactive)
1223 (setq dired-switches-alist nil)
1224 (revert-buffer))
1225 \f
1226 (defun dired-update-file-line (file)
1227 ;; Delete the current line, and insert an entry for FILE.
1228 ;; If FILE is nil, then just delete the current line.
1229 ;; Keeps any marks that may be present in column one (doing this
1230 ;; here is faster than with dired-add-entry's optional arg).
1231 ;; Does not update other dired buffers. Use dired-relist-entry for that.
1232 (let* ((opoint (line-beginning-position))
1233 (char (char-after opoint))
1234 (buffer-read-only))
1235 (delete-region opoint (progn (forward-line 1) (point)))
1236 (if file
1237 (progn
1238 (dired-add-entry file nil t)
1239 ;; Replace space by old marker without moving point.
1240 ;; Faster than goto+insdel inside a save-excursion?
1241 (when char
1242 (subst-char-in-region opoint (1+ opoint) ?\040 char)))))
1243 (dired-move-to-filename))
1244
1245 ;;;###autoload
1246 (defun dired-add-file (filename &optional marker-char)
1247 (dired-fun-in-all-buffers
1248 (file-name-directory filename) (file-name-nondirectory filename)
1249 (function dired-add-entry) filename marker-char))
1250
1251 (defvar dired-omit-mode)
1252 (declare-function dired-omit-regexp "dired-x" ())
1253 (defvar dired-omit-localp)
1254
1255 (defun dired-add-entry (filename &optional marker-char relative)
1256 "Add a new dired entry for FILENAME.
1257 Optionally mark it with MARKER-CHAR (a character, else uses
1258 `dired-marker-char'). Note that this adds the entry `out of order'
1259 if files are sorted by time, etc.
1260 Skips files that match `dired-trivial-filenames'.
1261 Exposes hidden subdirectories if a file is added there.
1262
1263 If `dired-x' is loaded and `dired-omit-mode' is enabled, skips
1264 files matching `dired-omit-regexp'."
1265 (if (or (not (featurep 'dired-x))
1266 (not dired-omit-mode)
1267 ;; Avoid calling ls for files that are going to be omitted anyway.
1268 (let ((omit-re (dired-omit-regexp)))
1269 (or (string= omit-re "")
1270 (not (string-match-p omit-re
1271 (cond
1272 ((eq 'no-dir dired-omit-localp)
1273 filename)
1274 ((eq t dired-omit-localp)
1275 (dired-make-relative filename))
1276 (t
1277 (dired-make-absolute
1278 filename
1279 (file-name-directory filename)))))))))
1280 ;; Do it!
1281 (progn
1282 (setq filename (directory-file-name filename))
1283 ;; Entry is always for files, even if they happen to also be directories
1284 (let* ((opoint (point))
1285 (cur-dir (dired-current-directory))
1286 (directory (if relative cur-dir (file-name-directory filename)))
1287 reason)
1288 (setq filename
1289 (if relative
1290 (file-relative-name filename directory)
1291 (file-name-nondirectory filename))
1292 reason
1293 (catch 'not-found
1294 (if (string= directory cur-dir)
1295 (progn
1296 (skip-chars-forward "^\r\n")
1297 (if (eq (following-char) ?\r)
1298 (dired-unhide-subdir))
1299 ;; We are already where we should be, except when
1300 ;; point is before the subdir line or its total line.
1301 (let ((p (dired-after-subdir-garbage cur-dir)))
1302 (if (< (point) p)
1303 (goto-char p))))
1304 ;; else try to find correct place to insert
1305 (if (dired-goto-subdir directory)
1306 (progn ;; unhide if necessary
1307 (if (looking-at-p "\r")
1308 ;; Point is at end of subdir line.
1309 (dired-unhide-subdir))
1310 ;; found - skip subdir and `total' line
1311 ;; and uninteresting files like . and ..
1312 ;; This better not move into the next subdir!
1313 (dired-goto-next-nontrivial-file))
1314 ;; not found
1315 (throw 'not-found "Subdir not found")))
1316 (let (buffer-read-only opoint)
1317 (beginning-of-line)
1318 (setq opoint (point))
1319 ;; Don't expand `.'.
1320 ;; Show just the file name within directory.
1321 (let ((default-directory directory))
1322 (dired-insert-directory
1323 directory
1324 (concat dired-actual-switches " -d")
1325 (list filename)))
1326 (goto-char opoint)
1327 ;; Put in desired marker char.
1328 (when marker-char
1329 (let ((dired-marker-char
1330 (if (integerp marker-char) marker-char
1331 dired-marker-char)))
1332 (dired-mark nil)))
1333 ;; Compensate for a bug in ange-ftp.
1334 ;; It inserts the file's absolute name, rather than
1335 ;; the relative one. That may be hard to fix since it
1336 ;; is probably controlled by something in ftp.
1337 (goto-char opoint)
1338 (let ((inserted-name (dired-get-filename 'verbatim)))
1339 (if (file-name-directory inserted-name)
1340 (let (props)
1341 (end-of-line)
1342 (forward-char (- (length inserted-name)))
1343 (setq props (text-properties-at (point)))
1344 (delete-char (length inserted-name))
1345 (let ((pt (point)))
1346 (insert filename)
1347 (set-text-properties pt (point) props))
1348 (forward-char 1))
1349 (forward-line 1)))
1350 (forward-line -1)
1351 (if dired-after-readin-hook
1352 ;; The subdir-alist is not affected...
1353 (save-excursion ; ...so we can run it right now:
1354 (save-restriction
1355 (beginning-of-line)
1356 (narrow-to-region (point)
1357 (line-beginning-position 2))
1358 (run-hooks 'dired-after-readin-hook))))
1359 (dired-move-to-filename))
1360 ;; return nil if all went well
1361 nil))
1362 (if reason ; don't move away on failure
1363 (goto-char opoint))
1364 (not reason))) ; return t on success, nil else
1365 ;; Don't do it (dired-omit-mode).
1366 ;; Return t for success (perhaps we should return file-exists-p).
1367 t))
1368
1369 (defun dired-after-subdir-garbage (dir)
1370 ;; Return pos of first file line of DIR, skipping header and total
1371 ;; or wildcard lines.
1372 ;; Important: never moves into the next subdir.
1373 ;; DIR is assumed to be unhidden.
1374 (save-excursion
1375 (or (dired-goto-subdir dir) (error "This cannot happen"))
1376 (forward-line 1)
1377 (while (and (not (eolp)) ; don't cross subdir boundary
1378 (not (dired-move-to-filename)))
1379 (forward-line 1))
1380 (point)))
1381
1382 ;;;###autoload
1383 (defun dired-remove-file (file)
1384 (dired-fun-in-all-buffers
1385 (file-name-directory file) (file-name-nondirectory file)
1386 (function dired-remove-entry) file))
1387
1388 (defun dired-remove-entry (file)
1389 (save-excursion
1390 (and (dired-goto-file file)
1391 (let (buffer-read-only)
1392 (delete-region (progn (beginning-of-line) (point))
1393 (line-beginning-position 2))))))
1394
1395 ;;;###autoload
1396 (defun dired-relist-file (file)
1397 "Create or update the line for FILE in all Dired buffers it would belong in."
1398 (dired-fun-in-all-buffers (file-name-directory file)
1399 (file-name-nondirectory file)
1400 (function dired-relist-entry) file))
1401
1402 (defun dired-relist-entry (file)
1403 ;; Relist the line for FILE, or just add it if it did not exist.
1404 ;; FILE must be an absolute file name.
1405 (let (buffer-read-only marker)
1406 ;; If cursor is already on FILE's line delete-region will cause
1407 ;; save-excursion to fail because of floating makers,
1408 ;; moving point to beginning of line. Sigh.
1409 (save-excursion
1410 (and (dired-goto-file file)
1411 (delete-region (progn (beginning-of-line)
1412 (setq marker (following-char))
1413 (point))
1414 (line-beginning-position 2)))
1415 (setq file (directory-file-name file))
1416 (dired-add-entry file (if (eq ?\040 marker) nil marker)))))
1417 \f
1418 ;;; Copy, move/rename, making hard and symbolic links
1419
1420 (defcustom dired-backup-overwrite nil
1421 "Non-nil if Dired should ask about making backups before overwriting files.
1422 Special value `always' suppresses confirmation."
1423 :type '(choice (const :tag "off" nil)
1424 (const :tag "suppress" always)
1425 (other :tag "ask" t))
1426 :group 'dired)
1427
1428 ;; This is a fluid var used in dired-handle-overwrite. It should be
1429 ;; let-bound whenever dired-copy-file etc are called. See
1430 ;; dired-create-files for an example.
1431 (defvar dired-overwrite-confirmed)
1432
1433 (defun dired-handle-overwrite (to)
1434 ;; Save old version of file TO that is to be overwritten.
1435 ;; `dired-overwrite-confirmed' and `overwrite-backup-query' are fluid vars
1436 ;; from dired-create-files.
1437 (let (backup)
1438 (when (and dired-backup-overwrite
1439 dired-overwrite-confirmed
1440 (setq backup (car (find-backup-file-name to)))
1441 (or (eq 'always dired-backup-overwrite)
1442 (dired-query 'overwrite-backup-query
1443 "Make backup for existing file `%s'? "
1444 to)))
1445 (rename-file to backup 0) ; confirm overwrite of old backup
1446 (dired-relist-entry backup))))
1447
1448 ;;;###autoload
1449 (defun dired-copy-file (from to ok-flag)
1450 (dired-handle-overwrite to)
1451 (dired-copy-file-recursive from to ok-flag dired-copy-preserve-time t
1452 dired-recursive-copies))
1453
1454 (declare-function make-symbolic-link "fileio.c")
1455
1456 (defun dired-copy-file-recursive (from to ok-flag &optional
1457 preserve-time top recursive)
1458 (when (and (eq t (car (file-attributes from)))
1459 (file-in-directory-p to from))
1460 (error "Cannot copy `%s' into its subdirectory `%s'" from to))
1461 (let ((attrs (file-attributes from)))
1462 (if (and recursive
1463 (eq t (car attrs))
1464 (or (eq recursive 'always)
1465 (yes-or-no-p (format "Recursive copies of %s? " from))))
1466 (copy-directory from to preserve-time)
1467 (or top (dired-handle-overwrite to))
1468 (condition-case err
1469 (if (stringp (car attrs))
1470 ;; It is a symlink
1471 (make-symbolic-link (car attrs) to ok-flag)
1472 (copy-file from to ok-flag preserve-time))
1473 (file-date-error
1474 (push (dired-make-relative from)
1475 dired-create-files-failures)
1476 (dired-log "Can't set date on %s:\n%s\n" from err))))))
1477
1478 ;;;###autoload
1479 (defun dired-rename-file (file newname ok-if-already-exists)
1480 (dired-handle-overwrite newname)
1481 (rename-file file newname ok-if-already-exists) ; error is caught in -create-files
1482 ;; Silently rename the visited file of any buffer visiting this file.
1483 (and (get-file-buffer file)
1484 (with-current-buffer (get-file-buffer file)
1485 (set-visited-file-name newname nil t)))
1486 (dired-remove-file file)
1487 ;; See if it's an inserted subdir, and rename that, too.
1488 (dired-rename-subdir file newname))
1489
1490 (defun dired-rename-subdir (from-dir to-dir)
1491 (setq from-dir (file-name-as-directory from-dir)
1492 to-dir (file-name-as-directory to-dir))
1493 (dired-fun-in-all-buffers from-dir nil
1494 (function dired-rename-subdir-1) from-dir to-dir)
1495 ;; Update visited file name of all affected buffers
1496 (let ((expanded-from-dir (expand-file-name from-dir))
1497 (blist (buffer-list)))
1498 (while blist
1499 (with-current-buffer (car blist)
1500 (if (and buffer-file-name
1501 (dired-in-this-tree buffer-file-name expanded-from-dir))
1502 (let ((modflag (buffer-modified-p))
1503 (to-file (dired-replace-in-string
1504 (concat "^" (regexp-quote from-dir))
1505 to-dir
1506 buffer-file-name)))
1507 (set-visited-file-name to-file)
1508 (set-buffer-modified-p modflag))))
1509 (setq blist (cdr blist)))))
1510
1511 (defun dired-rename-subdir-1 (dir to)
1512 ;; Rename DIR to TO in headerlines and dired-subdir-alist, if DIR or
1513 ;; one of its subdirectories is expanded in this buffer.
1514 (let ((expanded-dir (expand-file-name dir))
1515 (alist dired-subdir-alist)
1516 (elt nil))
1517 (while alist
1518 (setq elt (car alist)
1519 alist (cdr alist))
1520 (if (dired-in-this-tree (car elt) expanded-dir)
1521 ;; ELT's subdir is affected by the rename
1522 (dired-rename-subdir-2 elt dir to)))
1523 (if (equal dir default-directory)
1524 ;; if top level directory was renamed, lots of things have to be
1525 ;; updated:
1526 (progn
1527 (dired-unadvertise dir) ; we no longer dired DIR...
1528 (setq default-directory to
1529 dired-directory (expand-file-name;; this is correct
1530 ;; with and without wildcards
1531 (file-name-nondirectory dired-directory)
1532 to))
1533 (let ((new-name (file-name-nondirectory
1534 (directory-file-name dired-directory))))
1535 ;; try to rename buffer, but just leave old name if new
1536 ;; name would already exist (don't try appending "<%d>")
1537 (or (get-buffer new-name)
1538 (rename-buffer new-name)))
1539 ;; ... we dired TO now:
1540 (dired-advertise)))))
1541
1542 (defun dired-rename-subdir-2 (elt dir to)
1543 ;; Update the headerline and dired-subdir-alist element, as well as
1544 ;; dired-switches-alist element, of directory described by
1545 ;; alist-element ELT to reflect the moving of DIR to TO. Thus, ELT
1546 ;; describes either DIR itself or a subdir of DIR.
1547 (save-excursion
1548 (let ((regexp (regexp-quote (directory-file-name dir)))
1549 (newtext (directory-file-name to))
1550 buffer-read-only)
1551 (goto-char (dired-get-subdir-min elt))
1552 ;; Update subdir headerline in buffer
1553 (if (not (looking-at dired-subdir-regexp))
1554 (error "%s not found where expected - dired-subdir-alist broken?"
1555 dir)
1556 (goto-char (match-beginning 1))
1557 (if (re-search-forward regexp (match-end 1) t)
1558 (replace-match newtext t t)
1559 (error "Expected to find `%s' in headerline of %s" dir (car elt))))
1560 ;; Update buffer-local dired-subdir-alist and dired-switches-alist
1561 (let ((cons (assoc-string (car elt) dired-switches-alist))
1562 (cur-dir (dired-normalize-subdir
1563 (dired-replace-in-string regexp newtext (car elt)))))
1564 (setcar elt cur-dir)
1565 (when cons (setcar cons cur-dir))))))
1566 \f
1567 ;; Bound in dired-create-files
1568 (defvar overwrite-query)
1569 (defvar overwrite-backup-query)
1570
1571 ;; The basic function for half a dozen variations on cp/mv/ln/ln -s.
1572 (defun dired-create-files (file-creator operation fn-list name-constructor
1573 &optional marker-char)
1574 "Create one or more new files from a list of existing files FN-LIST.
1575 This function also handles querying the user, updating Dired
1576 buffers, and displaying a success or failure message.
1577
1578 FILE-CREATOR should be a function. It is called once for each
1579 file in FN-LIST, and must create a new file, querying the user
1580 and updating Dired buffers as necessary. It should accept three
1581 arguments: the old file name, the new name, and an argument
1582 OK-IF-ALREADY-EXISTS with the same meaning as in `copy-file'.
1583
1584 OPERATION should be a capitalized string describing the operation
1585 performed (e.g. `Copy'). It is used for error logging.
1586
1587 FN-LIST is the list of files to copy (full absolute file names).
1588
1589 NAME-CONSTRUCTOR should be a function accepting a single
1590 argument, the name of an old file, and returning either the
1591 corresponding new file name or nil to skip.
1592
1593 If optional argument MARKER-CHAR is non-nil, mark each
1594 newly-created file's Dired entry with the character MARKER-CHAR,
1595 or with the current marker character if MARKER-CHAR is t."
1596 (let (dired-create-files-failures failures
1597 skipped (success-count 0) (total (length fn-list)))
1598 (let (to overwrite-query
1599 overwrite-backup-query) ; for dired-handle-overwrite
1600 (dolist (from fn-list)
1601 (setq to (funcall name-constructor from))
1602 (if (equal to from)
1603 (progn
1604 (setq to nil)
1605 (dired-log "Cannot %s to same file: %s\n"
1606 (downcase operation) from)))
1607 (if (not to)
1608 (setq skipped (cons (dired-make-relative from) skipped))
1609 (let* ((overwrite (file-exists-p to))
1610 (dired-overwrite-confirmed ; for dired-handle-overwrite
1611 (and overwrite
1612 (let ((help-form '(format-message "\
1613 Type SPC or `y' to overwrite file `%s',
1614 DEL or `n' to skip to next,
1615 ESC or `q' to not overwrite any of the remaining files,
1616 `!' to overwrite all remaining files with no more questions." to)))
1617 (dired-query 'overwrite-query
1618 "Overwrite `%s'?" to))))
1619 ;; must determine if FROM is marked before file-creator
1620 ;; gets a chance to delete it (in case of a move).
1621 (actual-marker-char
1622 (cond ((integerp marker-char) marker-char)
1623 (marker-char (dired-file-marker from)) ; slow
1624 (t nil))))
1625 ;; Handle the `dired-copy-file' file-creator specially
1626 ;; When copying a directory to another directory or
1627 ;; possibly to itself or one of its subdirectories.
1628 ;; e.g "~/foo/" => "~/test/"
1629 ;; or "~/foo/" =>"~/foo/"
1630 ;; or "~/foo/ => ~/foo/bar/")
1631 ;; In this case the 'name-constructor' have set the destination
1632 ;; TO to "~/test/foo" because the old emacs23 behavior
1633 ;; of `copy-directory' was to not create the subdirectory
1634 ;; and instead copy the contents.
1635 ;; With the new behavior of `copy-directory'
1636 ;; (similar to the `cp' shell command) we don't
1637 ;; need such a construction of the target directory,
1638 ;; so modify the destination TO to "~/test/" instead of "~/test/foo/".
1639 (let ((destname (file-name-directory to)))
1640 (when (and (file-directory-p from)
1641 (file-directory-p to)
1642 (eq file-creator 'dired-copy-file))
1643 (setq to destname))
1644 ;; If DESTNAME is a subdirectory of FROM, not a symlink,
1645 ;; and the method in use is copying, signal an error.
1646 (and (eq t (car (file-attributes destname)))
1647 (eq file-creator 'dired-copy-file)
1648 (file-in-directory-p destname from)
1649 (error "Cannot copy `%s' into its subdirectory `%s'"
1650 from to)))
1651 (condition-case err
1652 (progn
1653 (funcall file-creator from to dired-overwrite-confirmed)
1654 (if overwrite
1655 ;; If we get here, file-creator hasn't been aborted
1656 ;; and the old entry (if any) has to be deleted
1657 ;; before adding the new entry.
1658 (dired-remove-file to))
1659 (setq success-count (1+ success-count))
1660 (message "%s: %d of %d" operation success-count total)
1661 (dired-add-file to actual-marker-char))
1662 (file-error ; FILE-CREATOR aborted
1663 (progn
1664 (push (dired-make-relative from)
1665 failures)
1666 (dired-log "%s `%s' to `%s' failed:\n%s\n"
1667 operation from to err))))))))
1668 (cond
1669 (dired-create-files-failures
1670 (setq failures (nconc failures dired-create-files-failures))
1671 (dired-log-summary
1672 (format "%s failed for %d file%s in %d requests"
1673 operation (length failures)
1674 (dired-plural-s (length failures))
1675 total)
1676 failures))
1677 (failures
1678 (dired-log-summary
1679 (format "%s failed for %d of %d file%s"
1680 operation (length failures)
1681 total (dired-plural-s total))
1682 failures))
1683 (skipped
1684 (dired-log-summary
1685 (format "%s: %d of %d file%s skipped"
1686 operation (length skipped) total
1687 (dired-plural-s total))
1688 skipped))
1689 (t
1690 (message "%s: %s file%s"
1691 operation success-count (dired-plural-s success-count)))))
1692 (dired-move-to-filename))
1693 \f
1694 (defun dired-do-create-files (op-symbol file-creator operation arg
1695 &optional marker-char op1
1696 how-to)
1697 "Create a new file for each marked file.
1698 Prompt user for a target directory in which to create the new
1699 files. The target may also be a non-directory file, if only
1700 one file is marked. The initial suggestion for target is the
1701 Dired buffer's current directory (or, if `dired-dwim-target' is
1702 non-nil, the current directory of a neighboring Dired window).
1703 OP-SYMBOL is the symbol for the operation. Function `dired-mark-pop-up'
1704 will determine whether pop-ups are appropriate for this OP-SYMBOL.
1705 FILE-CREATOR and OPERATION as in `dired-create-files'.
1706 ARG as in `dired-get-marked-files'.
1707 Optional arg MARKER-CHAR as in `dired-create-files'.
1708 Optional arg OP1 is an alternate form for OPERATION if there is
1709 only one file.
1710 Optional arg HOW-TO determines how to treat the target.
1711 If HOW-TO is nil, use `file-directory-p' to determine if the
1712 target is a directory. If so, the marked file(s) are created
1713 inside that directory. Otherwise, the target is a plain file;
1714 an error is raised unless there is exactly one marked file.
1715 If HOW-TO is t, target is always treated as a plain file.
1716 Otherwise, HOW-TO should be a function of one argument, TARGET.
1717 If its return value is nil, TARGET is regarded as a plain file.
1718 If it return value is a list, TARGET is a generalized
1719 directory (e.g. some sort of archive). The first element of
1720 this list must be a function with at least four arguments:
1721 operation - as OPERATION above.
1722 rfn-list - list of the relative names for the marked files.
1723 fn-list - list of the absolute names for the marked files.
1724 target - the name of the target itself.
1725 The rest of into-dir are optional arguments.
1726 For any other return value, TARGET is treated as a directory."
1727 (or op1 (setq op1 operation))
1728 (let* ((fn-list (dired-get-marked-files nil arg))
1729 (rfn-list (mapcar (function dired-make-relative) fn-list))
1730 (dired-one-file ; fluid variable inside dired-create-files
1731 (and (consp fn-list) (null (cdr fn-list)) (car fn-list)))
1732 (target-dir (dired-dwim-target-directory))
1733 (default (and dired-one-file
1734 (expand-file-name (file-name-nondirectory (car fn-list))
1735 target-dir)))
1736 (defaults (dired-dwim-target-defaults fn-list target-dir))
1737 (target (expand-file-name ; fluid variable inside dired-create-files
1738 (minibuffer-with-setup-hook
1739 (lambda ()
1740 (set (make-local-variable 'minibuffer-default-add-function) nil)
1741 (setq minibuffer-default defaults))
1742 (dired-mark-read-file-name
1743 (concat (if dired-one-file op1 operation) " %s to: ")
1744 target-dir op-symbol arg rfn-list default))))
1745 (into-dir (cond ((null how-to)
1746 ;; Allow DOS/Windows users to change the letter
1747 ;; case of a directory. If we don't test these
1748 ;; conditions up front, file-directory-p below
1749 ;; will return t because the filesystem is
1750 ;; case-insensitive, and Emacs will try to move
1751 ;; foo -> foo/foo, which fails.
1752 (if (and (memq system-type '(ms-dos windows-nt cygwin))
1753 (eq op-symbol 'move)
1754 dired-one-file
1755 (string= (downcase
1756 (expand-file-name (car fn-list)))
1757 (downcase
1758 (expand-file-name target)))
1759 (not (string=
1760 (file-name-nondirectory (car fn-list))
1761 (file-name-nondirectory target))))
1762 nil
1763 (file-directory-p target)))
1764 ((eq how-to t) nil)
1765 (t (funcall how-to target)))))
1766 (if (and (consp into-dir) (functionp (car into-dir)))
1767 (apply (car into-dir) operation rfn-list fn-list target (cdr into-dir))
1768 (if (not (or dired-one-file into-dir))
1769 (error "Marked %s: target must be a directory: %s" operation target))
1770 ;; rename-file bombs when moving directories unless we do this:
1771 (or into-dir (setq target (directory-file-name target)))
1772 (dired-create-files
1773 file-creator operation fn-list
1774 (if into-dir ; target is a directory
1775 ;; This function uses fluid variable target when called
1776 ;; inside dired-create-files:
1777 (function
1778 (lambda (from)
1779 (expand-file-name (file-name-nondirectory from) target)))
1780 (function (lambda (_from) target)))
1781 marker-char))))
1782
1783 ;; Read arguments for a marked-files command that wants a file name,
1784 ;; perhaps popping up the list of marked files.
1785 ;; ARG is the prefix arg and indicates whether the files came from
1786 ;; marks (ARG=nil) or a repeat factor (integerp ARG).
1787 ;; If the current file was used, the list has but one element and ARG
1788 ;; does not matter. (It is non-nil, non-integer in that case, namely '(4)).
1789 ;; DEFAULT is the default value to return if the user just hits RET;
1790 ;; if it is omitted or nil, then the name of the directory is used.
1791
1792 (defun dired-mark-read-file-name (prompt dir op-symbol arg files
1793 &optional default)
1794 (dired-mark-pop-up
1795 nil op-symbol files
1796 (function read-file-name)
1797 (format prompt (dired-mark-prompt arg files)) dir default))
1798
1799 (defun dired-dwim-target-directory ()
1800 ;; Try to guess which target directory the user may want.
1801 ;; If there is a dired buffer displayed in one of the next windows,
1802 ;; use its current subdir, else use current subdir of this dired buffer.
1803 (let ((this-dir (and (eq major-mode 'dired-mode)
1804 (dired-current-directory))))
1805 ;; non-dired buffer may want to profit from this function, e.g. vm-uudecode
1806 (if dired-dwim-target
1807 (let* ((other-win (get-window-with-predicate
1808 (lambda (window)
1809 (with-current-buffer (window-buffer window)
1810 (eq major-mode 'dired-mode)))))
1811 (other-dir (and other-win
1812 (with-current-buffer (window-buffer other-win)
1813 (and (eq major-mode 'dired-mode)
1814 (dired-current-directory))))))
1815 (or other-dir this-dir))
1816 this-dir)))
1817
1818 (defun dired-dwim-target-defaults (fn-list target-dir)
1819 ;; Return a list of default values for file-reading functions in Dired.
1820 ;; This list may contain directories from Dired buffers in other windows.
1821 ;; `fn-list' is a list of file names used to build a list of defaults.
1822 ;; When nil or more than one element, a list of defaults will
1823 ;; contain only directory names. `target-dir' is a directory name
1824 ;; to exclude from the returned list, for the case when this
1825 ;; directory name is already presented in initial input.
1826 ;; For Dired operations that support `dired-dwim-target',
1827 ;; the argument `target-dir' should have the value returned
1828 ;; from `dired-dwim-target-directory'.
1829 (let ((dired-one-file
1830 (and (consp fn-list) (null (cdr fn-list)) (car fn-list)))
1831 (current-dir (and (eq major-mode 'dired-mode)
1832 (dired-current-directory)))
1833 dired-dirs)
1834 ;; Get a list of directories of visible buffers in dired-mode.
1835 (walk-windows (lambda (w)
1836 (with-current-buffer (window-buffer w)
1837 (and (eq major-mode 'dired-mode)
1838 (push (dired-current-directory) dired-dirs)))))
1839 ;; Force the current dir to be the first in the list.
1840 (setq dired-dirs
1841 (delete-dups (delq nil (cons current-dir (nreverse dired-dirs)))))
1842 ;; Remove the target dir (if specified) or the current dir from
1843 ;; default values, because it should be already in initial input.
1844 (setq dired-dirs (delete (or target-dir current-dir) dired-dirs))
1845 ;; Return a list of default values.
1846 (if dired-one-file
1847 ;; For one file operation, provide a list that contains
1848 ;; other directories, other directories with the appended filename
1849 ;; and the current directory with the appended filename, e.g.
1850 ;; 1. /TARGET-DIR/
1851 ;; 2. /TARGET-DIR/FILENAME
1852 ;; 3. /CURRENT-DIR/FILENAME
1853 (append dired-dirs
1854 (mapcar (lambda (dir)
1855 (expand-file-name
1856 (file-name-nondirectory (car fn-list)) dir))
1857 (reverse dired-dirs))
1858 (list (expand-file-name
1859 (file-name-nondirectory (car fn-list))
1860 (or target-dir current-dir))))
1861 ;; For multi-file operation, return only a list of other directories.
1862 dired-dirs)))
1863
1864 \f
1865 ;;;###autoload
1866 (defun dired-create-directory (directory)
1867 "Create a directory called DIRECTORY.
1868 If DIRECTORY already exists, signal an error."
1869 (interactive
1870 (list (read-file-name "Create directory: " (dired-current-directory))))
1871 (let* ((expanded (directory-file-name (expand-file-name directory)))
1872 (try expanded) new)
1873 (if (file-exists-p expanded)
1874 (error "Cannot create directory %s: file exists" expanded))
1875 ;; Find the topmost nonexistent parent dir (variable `new')
1876 (while (and try (not (file-exists-p try)) (not (equal new try)))
1877 (setq new try
1878 try (directory-file-name (file-name-directory try))))
1879 (make-directory expanded t)
1880 (when new
1881 (dired-add-file new)
1882 (dired-move-to-filename))))
1883
1884 (defun dired-into-dir-with-symlinks (target)
1885 (and (file-directory-p target)
1886 (not (file-symlink-p target))))
1887 ;; This may not always be what you want, especially if target is your
1888 ;; home directory and it happens to be a symbolic link, as is often the
1889 ;; case with NFS and automounters. Or if you want to make symlinks
1890 ;; into directories that themselves are only symlinks, also quite
1891 ;; common.
1892
1893 ;; So we don't use this function as value for HOW-TO in
1894 ;; dired-do-symlink, which has the minor disadvantage of
1895 ;; making links *into* a symlinked-dir, when you really wanted to
1896 ;; *overwrite* that symlink. In that (rare, I guess) case, you'll
1897 ;; just have to remove that symlink by hand before making your marked
1898 ;; symlinks.
1899
1900 (defvar dired-copy-how-to-fn nil
1901 "Either nil or a function used by `dired-do-copy' to determine target.
1902 See HOW-TO argument for `dired-do-create-files'.")
1903
1904 ;;;###autoload
1905 (defun dired-do-copy (&optional arg)
1906 "Copy all marked (or next ARG) files, or copy the current file.
1907 When operating on just the current file, prompt for the new name.
1908
1909 When operating on multiple or marked files, prompt for a target
1910 directory, and make the new copies in that directory, with the
1911 same names as the original files. The initial suggestion for the
1912 target directory is the Dired buffer's current directory (or, if
1913 `dired-dwim-target' is non-nil, the current directory of a
1914 neighboring Dired window).
1915
1916 If `dired-copy-preserve-time' is non-nil, this command preserves
1917 the modification time of each old file in the copy, similar to
1918 the \"-p\" option for the \"cp\" shell command.
1919
1920 This command copies symbolic links by creating new ones, similar
1921 to the \"-d\" option for the \"cp\" shell command."
1922 (interactive "P")
1923 (let ((dired-recursive-copies dired-recursive-copies))
1924 (dired-do-create-files 'copy (function dired-copy-file)
1925 "Copy"
1926 arg dired-keep-marker-copy
1927 nil dired-copy-how-to-fn)))
1928
1929 ;;;###autoload
1930 (defun dired-do-symlink (&optional arg)
1931 "Make symbolic links to current file or all marked (or next ARG) files.
1932 When operating on just the current file, you specify the new name.
1933 When operating on multiple or marked files, you specify a directory
1934 and new symbolic links are made in that directory
1935 with the same names that the files currently have. The default
1936 suggested for the target directory depends on the value of
1937 `dired-dwim-target', which see.
1938
1939 For relative symlinks, use \\[dired-do-relsymlink]."
1940 (interactive "P")
1941 (dired-do-create-files 'symlink (function make-symbolic-link)
1942 "Symlink" arg dired-keep-marker-symlink))
1943
1944 ;;;###autoload
1945 (defun dired-do-hardlink (&optional arg)
1946 "Add names (hard links) current file or all marked (or next ARG) files.
1947 When operating on just the current file, you specify the new name.
1948 When operating on multiple or marked files, you specify a directory
1949 and new hard links are made in that directory
1950 with the same names that the files currently have. The default
1951 suggested for the target directory depends on the value of
1952 `dired-dwim-target', which see."
1953 (interactive "P")
1954 (dired-do-create-files 'hardlink (function dired-hardlink)
1955 "Hardlink" arg dired-keep-marker-hardlink))
1956
1957 (defun dired-hardlink (file newname &optional ok-if-already-exists)
1958 (dired-handle-overwrite newname)
1959 ;; error is caught in -create-files
1960 (add-name-to-file file newname ok-if-already-exists)
1961 ;; Update the link count
1962 (dired-relist-file file))
1963
1964 ;;;###autoload
1965 (defun dired-do-rename (&optional arg)
1966 "Rename current file or all marked (or next ARG) files.
1967 When renaming just the current file, you specify the new name.
1968 When renaming multiple or marked files, you specify a directory.
1969 This command also renames any buffers that are visiting the files.
1970 The default suggested for the target directory depends on the value
1971 of `dired-dwim-target', which see."
1972 (interactive "P")
1973 (dired-do-create-files 'move (function dired-rename-file)
1974 "Move" arg dired-keep-marker-rename "Rename"))
1975 ;;;###end dired-cp.el
1976 \f
1977 ;;; 5K
1978 ;;;###begin dired-re.el
1979 (defvar rename-regexp-query)
1980
1981 (defun dired-do-create-files-regexp
1982 (file-creator operation arg regexp newname &optional whole-name marker-char)
1983 ;; Create a new file for each marked file using regexps.
1984 ;; FILE-CREATOR and OPERATION as in dired-create-files.
1985 ;; ARG as in dired-get-marked-files.
1986 ;; Matches each marked file against REGEXP and constructs the new
1987 ;; filename from NEWNAME (like in function replace-match).
1988 ;; Optional arg WHOLE-NAME means match/replace the whole file name
1989 ;; instead of only the non-directory part of the file.
1990 ;; Optional arg MARKER-CHAR as in dired-create-files.
1991 (let* ((fn-list (dired-get-marked-files nil arg))
1992 (operation-prompt (concat operation " `%s' to `%s'?"))
1993 (rename-regexp-help-form (format-message "\
1994 Type SPC or `y' to %s one match, DEL or `n' to skip to next,
1995 `!' to %s all remaining matches with no more questions."
1996 (downcase operation)
1997 (downcase operation)))
1998 (regexp-name-constructor
1999 ;; Function to construct new filename using REGEXP and NEWNAME:
2000 (if whole-name ; easy (but rare) case
2001 (function
2002 (lambda (from)
2003 (let ((to (dired-string-replace-match regexp from newname))
2004 ;; must bind help-form directly around call to
2005 ;; dired-query
2006 (help-form rename-regexp-help-form))
2007 (if to
2008 (and (dired-query 'rename-regexp-query
2009 operation-prompt
2010 from
2011 to)
2012 to)
2013 (dired-log "%s: %s did not match regexp %s\n"
2014 operation from regexp)))))
2015 ;; not whole-name, replace non-directory part only
2016 (function
2017 (lambda (from)
2018 (let* ((new (dired-string-replace-match
2019 regexp (file-name-nondirectory from) newname))
2020 (to (and new ; nil means there was no match
2021 (expand-file-name new
2022 (file-name-directory from))))
2023 (help-form rename-regexp-help-form))
2024 (if to
2025 (and (dired-query 'rename-regexp-query
2026 operation-prompt
2027 (dired-make-relative from)
2028 (dired-make-relative to))
2029 to)
2030 (dired-log "%s: %s did not match regexp %s\n"
2031 operation (file-name-nondirectory from) regexp)))))))
2032 rename-regexp-query)
2033 (dired-create-files
2034 file-creator operation fn-list regexp-name-constructor marker-char)))
2035
2036 (defun dired-mark-read-regexp (operation)
2037 ;; Prompt user about performing OPERATION.
2038 ;; Read and return list of: regexp newname arg whole-name.
2039 (let* ((whole-name
2040 (equal 0 (prefix-numeric-value current-prefix-arg)))
2041 (arg
2042 (if whole-name nil current-prefix-arg))
2043 (regexp
2044 (read-regexp
2045 (concat (if whole-name "Abs. " "") operation " from (regexp): ")
2046 nil 'dired-regexp-history))
2047 (newname
2048 (read-string
2049 (concat (if whole-name "Abs. " "") operation " " regexp " to: "))))
2050 (list regexp newname arg whole-name)))
2051
2052 ;;;###autoload
2053 (defun dired-do-rename-regexp (regexp newname &optional arg whole-name)
2054 "Rename selected files whose names match REGEXP to NEWNAME.
2055
2056 With non-zero prefix argument ARG, the command operates on the next ARG
2057 files. Otherwise, it operates on all the marked files, or the current
2058 file if none are marked.
2059
2060 As each match is found, the user must type a character saying
2061 what to do with it. For directions, type \\[help-command] at that time.
2062 NEWNAME may contain \\=\\<n> or \\& as in `query-replace-regexp'.
2063 REGEXP defaults to the last regexp used.
2064
2065 With a zero prefix arg, renaming by regexp affects the absolute file name.
2066 Normally, only the non-directory part of the file name is used and changed."
2067 (interactive (dired-mark-read-regexp "Rename"))
2068 (dired-do-create-files-regexp
2069 (function dired-rename-file)
2070 "Rename" arg regexp newname whole-name dired-keep-marker-rename))
2071
2072 ;;;###autoload
2073 (defun dired-do-copy-regexp (regexp newname &optional arg whole-name)
2074 "Copy selected files whose names match REGEXP to NEWNAME.
2075 See function `dired-do-rename-regexp' for more info."
2076 (interactive (dired-mark-read-regexp "Copy"))
2077 (let ((dired-recursive-copies nil)) ; No recursive copies.
2078 (dired-do-create-files-regexp
2079 (function dired-copy-file)
2080 (if dired-copy-preserve-time "Copy [-p]" "Copy")
2081 arg regexp newname whole-name dired-keep-marker-copy)))
2082
2083 ;;;###autoload
2084 (defun dired-do-hardlink-regexp (regexp newname &optional arg whole-name)
2085 "Hardlink selected files whose names match REGEXP to NEWNAME.
2086 See function `dired-do-rename-regexp' for more info."
2087 (interactive (dired-mark-read-regexp "HardLink"))
2088 (dired-do-create-files-regexp
2089 (function add-name-to-file)
2090 "HardLink" arg regexp newname whole-name dired-keep-marker-hardlink))
2091
2092 ;;;###autoload
2093 (defun dired-do-symlink-regexp (regexp newname &optional arg whole-name)
2094 "Symlink selected files whose names match REGEXP to NEWNAME.
2095 See function `dired-do-rename-regexp' for more info."
2096 (interactive (dired-mark-read-regexp "SymLink"))
2097 (dired-do-create-files-regexp
2098 (function make-symbolic-link)
2099 "SymLink" arg regexp newname whole-name dired-keep-marker-symlink))
2100
2101 (defvar rename-non-directory-query)
2102
2103 (defun dired-create-files-non-directory
2104 (file-creator basename-constructor operation arg)
2105 ;; Perform FILE-CREATOR on the non-directory part of marked files
2106 ;; using function BASENAME-CONSTRUCTOR, with query for each file.
2107 ;; OPERATION like in dired-create-files, ARG as in dired-get-marked-files.
2108 (let (rename-non-directory-query)
2109 (dired-create-files
2110 file-creator
2111 operation
2112 (dired-get-marked-files nil arg)
2113 (function
2114 (lambda (from)
2115 (let ((to (concat (file-name-directory from)
2116 (funcall basename-constructor
2117 (file-name-nondirectory from)))))
2118 (and (let ((help-form (format-message "\
2119 Type SPC or `y' to %s one file, DEL or `n' to skip to next,
2120 `!' to %s all remaining matches with no more questions."
2121 (downcase operation)
2122 (downcase operation))))
2123 (dired-query 'rename-non-directory-query
2124 (concat operation " `%s' to `%s'")
2125 (dired-make-relative from)
2126 (dired-make-relative to)))
2127 to))))
2128 dired-keep-marker-rename)))
2129
2130 (defun dired-rename-non-directory (basename-constructor operation arg)
2131 (dired-create-files-non-directory
2132 (function dired-rename-file)
2133 basename-constructor operation arg))
2134
2135 ;;;###autoload
2136 (defun dired-upcase (&optional arg)
2137 "Rename all marked (or next ARG) files to upper case."
2138 (interactive "P")
2139 (dired-rename-non-directory (function upcase) "Rename upcase" arg))
2140
2141 ;;;###autoload
2142 (defun dired-downcase (&optional arg)
2143 "Rename all marked (or next ARG) files to lower case."
2144 (interactive "P")
2145 (dired-rename-non-directory (function downcase) "Rename downcase" arg))
2146
2147 ;;;###end dired-re.el
2148 \f
2149 ;;; 13K
2150 ;;;###begin dired-ins.el
2151
2152 ;;;###autoload
2153 (defun dired-maybe-insert-subdir (dirname &optional
2154 switches no-error-if-not-dir-p)
2155 "Insert this subdirectory into the same dired buffer.
2156 If it is already present, just move to it (type \\[dired-do-redisplay] to refresh),
2157 else inserts it at its natural place (as `ls -lR' would have done).
2158 With a prefix arg, you may edit the ls switches used for this listing.
2159 You can add `R' to the switches to expand the whole tree starting at
2160 this subdirectory.
2161 This function takes some pains to conform to `ls -lR' output.
2162
2163 Dired remembers switches specified with a prefix arg, so that reverting
2164 the buffer will not reset them. However, using `dired-undo' to re-insert
2165 or delete subdirectories can bypass this machinery. Hence, you sometimes
2166 may have to reset some subdirectory switches after a `dired-undo'.
2167 You can reset all subdirectory switches to the default using
2168 \\<dired-mode-map>\\[dired-reset-subdir-switches].
2169 See Info node `(emacs)Subdir switches' for more details."
2170 (interactive
2171 (list (dired-get-filename)
2172 (if current-prefix-arg
2173 (read-string "Switches for listing: "
2174 (or dired-subdir-switches dired-actual-switches)))))
2175 (let ((opoint (point)))
2176 ;; We don't need a marker for opoint as the subdir is always
2177 ;; inserted *after* opoint.
2178 (setq dirname (file-name-as-directory dirname))
2179 (or (and (not switches)
2180 (when (dired-goto-subdir dirname)
2181 (unless (dired-subdir-hidden-p dirname)
2182 (dired-initial-position dirname))
2183 t))
2184 (dired-insert-subdir dirname switches no-error-if-not-dir-p))
2185 ;; Push mark so that it's easy to find back. Do this after the
2186 ;; insert message so that the user sees the `Mark set' message.
2187 (push-mark opoint)))
2188
2189 ;;;###autoload
2190 (defun dired-insert-subdir (dirname &optional switches no-error-if-not-dir-p)
2191 "Insert this subdirectory into the same Dired buffer.
2192 If it is already present, overwrite the previous entry;
2193 otherwise, insert it at its natural place (as `ls -lR' would
2194 have done).
2195 With a prefix arg, you may edit the `ls' switches used for this listing.
2196 You can add `R' to the switches to expand the whole tree starting at
2197 this subdirectory.
2198 This function takes some pains to conform to `ls -lR' output."
2199 ;; NO-ERROR-IF-NOT-DIR-P needed for special filesystems like
2200 ;; Prospero where dired-ls does the right thing, but
2201 ;; file-directory-p has not been redefined.
2202 (interactive
2203 (list (dired-get-filename)
2204 (if current-prefix-arg
2205 (read-string "Switches for listing: "
2206 (or dired-subdir-switches dired-actual-switches)))))
2207 (setq dirname (file-name-as-directory (expand-file-name dirname)))
2208 (or no-error-if-not-dir-p
2209 (file-directory-p dirname)
2210 (error "Attempt to insert a non-directory: %s" dirname))
2211 (let ((elt (assoc dirname dired-subdir-alist))
2212 (cons (assoc-string dirname dired-switches-alist))
2213 (modflag (buffer-modified-p))
2214 (old-switches switches)
2215 switches-have-R mark-alist case-fold-search buffer-read-only)
2216 (and (not switches) cons (setq switches (cdr cons)))
2217 (dired-insert-subdir-validate dirname switches)
2218 ;; case-fold-search is nil now, so we can test for capital `R':
2219 (if (setq switches-have-R (and switches (string-match-p "R" switches)))
2220 ;; avoid duplicated subdirs
2221 (setq mark-alist (dired-kill-tree dirname t)))
2222 (if elt
2223 ;; If subdir is already present, remove it and remember its marks
2224 (setq mark-alist (nconc (dired-insert-subdir-del elt) mark-alist))
2225 (dired-insert-subdir-newpos dirname)) ; else compute new position
2226 (dired-insert-subdir-doupdate
2227 dirname elt (dired-insert-subdir-doinsert dirname switches))
2228 (when old-switches
2229 (if cons
2230 (setcdr cons switches)
2231 (push (cons dirname switches) dired-switches-alist)))
2232 (when switches-have-R
2233 (dired-build-subdir-alist switches)
2234 (setq switches (dired-replace-in-string "R" "" switches))
2235 (dolist (cur-ass dired-subdir-alist)
2236 (let ((cur-dir (car cur-ass)))
2237 (and (dired-in-this-tree cur-dir dirname)
2238 (let ((cur-cons (assoc-string cur-dir dired-switches-alist)))
2239 (if cur-cons
2240 (setcdr cur-cons switches)
2241 (push (cons cur-dir switches) dired-switches-alist)))))))
2242 (dired-initial-position dirname)
2243 (save-excursion (dired-mark-remembered mark-alist))
2244 (restore-buffer-modified-p modflag)))
2245
2246 (defun dired-insert-subdir-validate (dirname &optional switches)
2247 ;; Check that it is valid to insert DIRNAME with SWITCHES.
2248 ;; Signal an error if invalid (e.g. user typed `i' on `..').
2249 (or (dired-in-this-tree dirname (expand-file-name default-directory))
2250 (error "%s: not in this directory tree" dirname))
2251 (let ((real-switches (or switches dired-subdir-switches)))
2252 (when real-switches
2253 (let (case-fold-search)
2254 (mapcar
2255 (function
2256 (lambda (x)
2257 (or (eq (null (string-match-p x real-switches))
2258 (null (string-match-p x dired-actual-switches)))
2259 (error
2260 "Can't have dirs with and without -%s switches together" x))))
2261 ;; all switches that make a difference to dired-get-filename:
2262 '("F" "b"))))))
2263
2264 (defun dired-alist-add (dir new-marker)
2265 ;; Add new DIR at NEW-MARKER. Sort alist.
2266 (dired-alist-add-1 dir new-marker)
2267 (dired-alist-sort))
2268
2269 (defun dired-alist-sort ()
2270 ;; Keep the alist sorted on buffer position.
2271 (setq dired-subdir-alist
2272 (sort dired-subdir-alist
2273 (function (lambda (elt1 elt2)
2274 (> (dired-get-subdir-min elt1)
2275 (dired-get-subdir-min elt2)))))))
2276
2277 (defun dired-kill-tree (dirname &optional remember-marks kill-root)
2278 "Kill all proper subdirs of DIRNAME, excluding DIRNAME itself.
2279 Interactively, you can kill DIRNAME as well by using a prefix argument.
2280 In interactive use, the command prompts for DIRNAME.
2281
2282 When called from Lisp, if REMEMBER-MARKS is non-nil, return an alist
2283 of marked files. If KILL-ROOT is non-nil, kill DIRNAME as well."
2284 (interactive "DKill tree below directory: \ni\nP")
2285 (setq dirname (file-name-as-directory (expand-file-name dirname)))
2286 (let ((s-alist dired-subdir-alist) dir m-alist)
2287 (while s-alist
2288 (setq dir (car (car s-alist))
2289 s-alist (cdr s-alist))
2290 (and (or kill-root (not (string-equal dir dirname)))
2291 (dired-in-this-tree dir dirname)
2292 (dired-goto-subdir dir)
2293 (setq m-alist (nconc (dired-kill-subdir remember-marks) m-alist))))
2294 m-alist))
2295
2296 (defun dired-insert-subdir-newpos (new-dir)
2297 ;; Find pos for new subdir, according to tree order.
2298 ;;(goto-char (point-max))
2299 (let ((alist dired-subdir-alist) elt dir new-pos)
2300 (while alist
2301 (setq elt (car alist)
2302 alist (cdr alist)
2303 dir (car elt))
2304 (if (dired-tree-lessp dir new-dir)
2305 ;; Insert NEW-DIR after DIR
2306 (setq new-pos (dired-get-subdir-max elt)
2307 alist nil)))
2308 (goto-char new-pos))
2309 ;; want a separating newline between subdirs
2310 (or (eobp)
2311 (forward-line -1))
2312 (insert "\n")
2313 (point))
2314
2315 (defun dired-insert-subdir-del (element)
2316 ;; Erase an already present subdir (given by ELEMENT) from buffer.
2317 ;; Move to that buffer position. Return a mark-alist.
2318 (let ((begin-marker (dired-get-subdir-min element)))
2319 (goto-char begin-marker)
2320 ;; Are at beginning of subdir (and inside it!). Now determine its end:
2321 (goto-char (dired-subdir-max))
2322 (or (eobp);; want a separating newline _between_ subdirs:
2323 (forward-char -1))
2324 (prog1
2325 (dired-remember-marks begin-marker (point))
2326 (delete-region begin-marker (point)))))
2327
2328 (defun dired-insert-subdir-doinsert (dirname switches)
2329 ;; Insert ls output after point.
2330 ;; Return the boundary of the inserted text (as list of BEG and END).
2331 (save-excursion
2332 (let ((begin (point)))
2333 (let ((dired-actual-switches
2334 (or switches
2335 dired-subdir-switches
2336 (dired-replace-in-string "R" "" dired-actual-switches))))
2337 (if (equal dirname (car (car (last dired-subdir-alist))))
2338 ;; If doing the top level directory of the buffer,
2339 ;; redo it as specified in dired-directory.
2340 (dired-readin-insert)
2341 (dired-insert-directory dirname dired-actual-switches nil nil t)))
2342 (list begin (point)))))
2343
2344 (defun dired-insert-subdir-doupdate (dirname elt beg-end)
2345 ;; Point is at the correct subdir alist position for ELT,
2346 ;; BEG-END is the subdir-region (as list of begin and end).
2347 (if elt ; subdir was already present
2348 ;; update its position (should actually be unchanged)
2349 (set-marker (dired-get-subdir-min elt) (point-marker))
2350 (dired-alist-add dirname (point-marker)))
2351 ;; The hook may depend on the subdir-alist containing the just
2352 ;; inserted subdir, so run it after dired-alist-add:
2353 (if dired-after-readin-hook
2354 (save-excursion
2355 (let ((begin (nth 0 beg-end))
2356 (end (nth 1 beg-end)))
2357 (goto-char begin)
2358 (save-restriction
2359 (narrow-to-region begin end)
2360 ;; hook may add or delete lines, but the subdir boundary
2361 ;; marker floats
2362 (run-hooks 'dired-after-readin-hook))))))
2363
2364 (defun dired-tree-lessp (dir1 dir2)
2365 ;; Lexicographic order on file name components, like `ls -lR':
2366 ;; DIR1 < DIR2 if DIR1 comes *before* DIR2 in an `ls -lR' listing,
2367 ;; i.e., if DIR1 is a (grand)parent dir of DIR2,
2368 ;; or DIR1 and DIR2 are in the same parentdir and their last
2369 ;; components are string-lessp.
2370 ;; Thus ("/usr/" "/usr/bin") and ("/usr/a/" "/usr/b/") are tree-lessp.
2371 ;; string-lessp could arguably be replaced by file-newer-than-file-p
2372 ;; if dired-actual-switches contained t.
2373 (setq dir1 (file-name-as-directory dir1)
2374 dir2 (file-name-as-directory dir2))
2375 (let ((components-1 (dired-split "/" dir1))
2376 (components-2 (dired-split "/" dir2)))
2377 (while (and components-1
2378 components-2
2379 (equal (car components-1) (car components-2)))
2380 (setq components-1 (cdr components-1)
2381 components-2 (cdr components-2)))
2382 (let ((c1 (car components-1))
2383 (c2 (car components-2)))
2384
2385 (cond ((and c1 c2)
2386 (string-lessp c1 c2))
2387 ((and (null c1) (null c2))
2388 nil) ; they are equal, not lessp
2389 ((null c1) ; c2 is a subdir of c1: c1<c2
2390 t)
2391 ((null c2) ; c1 is a subdir of c2: c1>c2
2392 nil)
2393 (t (error "This can't happen"))))))
2394
2395 ;; There should be a builtin split function - inverse to mapconcat.
2396 (defun dired-split (pat str &optional limit)
2397 "Splitting on regexp PAT, turn string STR into a list of substrings.
2398 Optional third arg LIMIT (>= 1) is a limit to the length of the
2399 resulting list.
2400 Thus, if SEP is a regexp that only matches itself,
2401
2402 (mapconcat 'identity (dired-split SEP STRING) SEP)
2403
2404 is always equal to STRING."
2405 (let* ((start (string-match pat str))
2406 (result (list (substring str 0 start)))
2407 (count 1)
2408 (end (if start (match-end 0))))
2409 (if end ; else nothing left
2410 (while (and (or (not (integerp limit))
2411 (< count limit))
2412 (string-match pat str end))
2413 (setq start (match-beginning 0)
2414 count (1+ count)
2415 result (cons (substring str end start) result)
2416 end (match-end 0)
2417 start end)
2418 ))
2419 (if (and (or (not (integerp limit))
2420 (< count limit))
2421 end) ; else nothing left
2422 (setq result
2423 (cons (substring str end) result)))
2424 (nreverse result)))
2425 \f
2426 ;;; moving by subdirectories
2427
2428 ;;;###autoload
2429 (defun dired-prev-subdir (arg &optional no-error-if-not-found no-skip)
2430 "Go to previous subdirectory, regardless of level.
2431 When called interactively and not on a subdir line, go to this subdir's line."
2432 ;;(interactive "p")
2433 (interactive
2434 (list (if current-prefix-arg
2435 (prefix-numeric-value current-prefix-arg)
2436 ;; if on subdir start already, don't stay there!
2437 (if (dired-get-subdir) 1 0))))
2438 (dired-next-subdir (- arg) no-error-if-not-found no-skip))
2439
2440 (defun dired-subdir-min ()
2441 (save-excursion
2442 (if (not (dired-prev-subdir 0 t t))
2443 (error "Not in a subdir!")
2444 (point))))
2445
2446 ;;;###autoload
2447 (defun dired-goto-subdir (dir)
2448 "Go to end of header line of DIR in this dired buffer.
2449 Return value of point on success, otherwise return nil.
2450 The next char is either \\n, or \\r if DIR is hidden."
2451 (interactive
2452 (prog1 ; let push-mark display its message
2453 (list (expand-file-name
2454 (completing-read "Goto in situ directory: " ; prompt
2455 dired-subdir-alist ; table
2456 nil ; predicate
2457 t ; require-match
2458 (dired-current-directory))))
2459 (push-mark)))
2460 (setq dir (file-name-as-directory dir))
2461 (let ((elt (assoc dir dired-subdir-alist)))
2462 (and elt
2463 (goto-char (dired-get-subdir-min elt))
2464 ;; dired-subdir-hidden-p and dired-add-entry depend on point being
2465 ;; at either \r or \n after this function succeeds.
2466 (progn (skip-chars-forward "^\r\n")
2467 (point)))))
2468 \f
2469 ;;;###autoload
2470 (defun dired-mark-subdir-files ()
2471 "Mark all files except `.' and `..' in current subdirectory.
2472 If the Dired buffer shows multiple directories, this command
2473 marks the files listed in the subdirectory that point is in."
2474 (interactive)
2475 (let ((p-min (dired-subdir-min)))
2476 (dired-mark-files-in-region p-min (dired-subdir-max))))
2477
2478 ;;;###autoload
2479 (defun dired-kill-subdir (&optional remember-marks)
2480 "Remove all lines of current subdirectory.
2481 Lower levels are unaffected."
2482 ;; With optional REMEMBER-MARKS, return a mark-alist.
2483 (interactive)
2484 (let* ((beg (dired-subdir-min))
2485 (end (dired-subdir-max))
2486 (modflag (buffer-modified-p))
2487 (cur-dir (dired-current-directory))
2488 (cons (assoc-string cur-dir dired-switches-alist))
2489 buffer-read-only)
2490 (if (equal cur-dir default-directory)
2491 (error "Attempt to kill top level directory"))
2492 (prog1
2493 (if remember-marks (dired-remember-marks beg end))
2494 (delete-region beg end)
2495 (if (eobp) ; don't leave final blank line
2496 (delete-char -1))
2497 (dired-unsubdir cur-dir)
2498 (when cons
2499 (setq dired-switches-alist (delete cons dired-switches-alist)))
2500 (restore-buffer-modified-p modflag))))
2501
2502 (defun dired-unsubdir (dir)
2503 ;; Remove DIR from the alist
2504 (setq dired-subdir-alist
2505 (delq (assoc dir dired-subdir-alist) dired-subdir-alist)))
2506
2507 ;;;###autoload
2508 (defun dired-tree-up (arg)
2509 "Go up ARG levels in the dired tree."
2510 (interactive "p")
2511 (let ((dir (dired-current-directory)))
2512 (while (>= arg 1)
2513 (setq arg (1- arg)
2514 dir (file-name-directory (directory-file-name dir))))
2515 ;;(setq dir (expand-file-name dir))
2516 (or (dired-goto-subdir dir)
2517 (error "Cannot go up to %s - not in this tree" dir))))
2518
2519 ;;;###autoload
2520 (defun dired-tree-down ()
2521 "Go down in the dired tree."
2522 (interactive)
2523 (let ((dir (dired-current-directory)) ; has slash
2524 pos case-fold-search) ; filenames are case sensitive
2525 (let ((rest (reverse dired-subdir-alist)) elt)
2526 (while rest
2527 (setq elt (car rest)
2528 rest (cdr rest))
2529 (if (dired-in-this-tree (directory-file-name (car elt)) dir)
2530 (setq rest nil
2531 pos (dired-goto-subdir (car elt))))))
2532 (if pos
2533 (goto-char pos)
2534 (error "At the bottom"))))
2535 \f
2536 ;;; hiding
2537
2538 (defun dired-unhide-subdir ()
2539 (let (buffer-read-only)
2540 (subst-char-in-region (dired-subdir-min) (dired-subdir-max) ?\r ?\n)))
2541
2542 (defun dired-hide-check ()
2543 (or selective-display
2544 (error "selective-display must be t for subdir hiding to work!")))
2545
2546 (defun dired-subdir-hidden-p (dir)
2547 (and selective-display
2548 (save-excursion
2549 (dired-goto-subdir dir)
2550 (looking-at-p "\r"))))
2551
2552 ;;;###autoload
2553 (defun dired-hide-subdir (arg)
2554 "Hide or unhide the current subdirectory and move to next directory.
2555 Optional prefix arg is a repeat factor.
2556 Use \\[dired-hide-all] to (un)hide all directories."
2557 (interactive "p")
2558 (dired-hide-check)
2559 (let ((modflag (buffer-modified-p)))
2560 (while (>= (setq arg (1- arg)) 0)
2561 (let* ((cur-dir (dired-current-directory))
2562 (hidden-p (dired-subdir-hidden-p cur-dir))
2563 (elt (assoc cur-dir dired-subdir-alist))
2564 (end-pos (1- (dired-get-subdir-max elt)))
2565 buffer-read-only)
2566 ;; keep header line visible, hide rest
2567 (goto-char (dired-get-subdir-min elt))
2568 (skip-chars-forward "^\n\r")
2569 (if hidden-p
2570 (subst-char-in-region (point) end-pos ?\r ?\n)
2571 (subst-char-in-region (point) end-pos ?\n ?\r)))
2572 (dired-next-subdir 1 t))
2573 (restore-buffer-modified-p modflag)))
2574
2575 ;;;###autoload
2576 (defun dired-hide-all (&optional ignored)
2577 "Hide all subdirectories, leaving only their header lines.
2578 If there is already something hidden, make everything visible again.
2579 Use \\[dired-hide-subdir] to (un)hide a particular subdirectory."
2580 (interactive "P")
2581 (dired-hide-check)
2582 (let ((modflag (buffer-modified-p))
2583 buffer-read-only)
2584 (if (save-excursion
2585 (goto-char (point-min))
2586 (search-forward "\r" nil t))
2587 ;; unhide - bombs on \r in filenames
2588 (subst-char-in-region (point-min) (point-max) ?\r ?\n)
2589 ;; hide
2590 (let ((pos (point-max)) ; pos of end of last directory
2591 (alist dired-subdir-alist))
2592 (while alist ; while there are dirs before pos
2593 (subst-char-in-region (dired-get-subdir-min (car alist)) ; pos of prev dir
2594 (save-excursion
2595 (goto-char pos) ; current dir
2596 ;; we're somewhere on current dir's line
2597 (forward-line -1)
2598 (point))
2599 ?\n ?\r)
2600 (setq pos (dired-get-subdir-min (car alist))) ; prev dir gets current dir
2601 (setq alist (cdr alist)))))
2602 (restore-buffer-modified-p modflag)))
2603
2604 ;;;###end dired-ins.el
2605
2606 \f
2607 ;; Search only in file names in the Dired buffer.
2608
2609 (defcustom dired-isearch-filenames nil
2610 "Non-nil to Isearch in file names only.
2611 If t, Isearch in Dired always matches only file names.
2612 If `dwim', Isearch matches file names when initial point position is on
2613 a file name. Otherwise, it searches the whole buffer without restrictions."
2614 :type '(choice (const :tag "No restrictions" nil)
2615 (const :tag "When point is on a file name initially, search file names" dwim)
2616 (const :tag "Always search in file names" t))
2617 :group 'dired
2618 :version "23.1")
2619
2620 (define-minor-mode dired-isearch-filenames-mode
2621 "Toggle file names searching on or off.
2622 When on, Isearch skips matches outside file names using the predicate
2623 `dired-isearch-filter-filenames' that matches only at file names.
2624 When off, it uses the original predicate."
2625 nil nil nil
2626 (if dired-isearch-filenames-mode
2627 (add-function :before-while (local 'isearch-filter-predicate)
2628 #'dired-isearch-filter-filenames
2629 '((isearch-message-prefix . "filename ")))
2630 (remove-function (local 'isearch-filter-predicate)
2631 #'dired-isearch-filter-filenames))
2632 (when isearch-mode
2633 (setq isearch-success t isearch-adjusted t)
2634 (isearch-update)))
2635
2636 ;;;###autoload
2637 (defun dired-isearch-filenames-setup ()
2638 "Set up isearch to search in Dired file names.
2639 Intended to be added to `isearch-mode-hook'."
2640 (when (or (eq dired-isearch-filenames t)
2641 (and (eq dired-isearch-filenames 'dwim)
2642 (get-text-property (point) 'dired-filename)))
2643 (define-key isearch-mode-map "\M-sff" 'dired-isearch-filenames-mode)
2644 (dired-isearch-filenames-mode 1)
2645 (add-hook 'isearch-mode-end-hook 'dired-isearch-filenames-end nil t)))
2646
2647 (defun dired-isearch-filenames-end ()
2648 "Clean up the Dired file name search after terminating isearch."
2649 (define-key isearch-mode-map "\M-sff" nil)
2650 (dired-isearch-filenames-mode -1)
2651 (remove-hook 'isearch-mode-end-hook 'dired-isearch-filenames-end t))
2652
2653 (defun dired-isearch-filter-filenames (beg end)
2654 "Test whether the current search hit is a file name.
2655 Return non-nil if the text from BEG to END is part of a file
2656 name (has the text property `dired-filename')."
2657 (text-property-not-all (min beg end) (max beg end)
2658 'dired-filename nil))
2659
2660 ;;;###autoload
2661 (defun dired-isearch-filenames ()
2662 "Search for a string using Isearch only in file names in the Dired buffer."
2663 (interactive)
2664 (let ((dired-isearch-filenames t))
2665 (isearch-forward nil t)))
2666
2667 ;;;###autoload
2668 (defun dired-isearch-filenames-regexp ()
2669 "Search for a regexp using Isearch only in file names in the Dired buffer."
2670 (interactive)
2671 (let ((dired-isearch-filenames t))
2672 (isearch-forward-regexp nil t)))
2673
2674 \f
2675 ;; Functions for searching in tags style among marked files.
2676
2677 ;;;###autoload
2678 (defun dired-do-isearch ()
2679 "Search for a string through all marked files using Isearch."
2680 (interactive)
2681 (multi-isearch-files
2682 (dired-get-marked-files nil nil 'dired-nondirectory-p)))
2683
2684 ;;;###autoload
2685 (defun dired-do-isearch-regexp ()
2686 "Search for a regexp through all marked files using Isearch."
2687 (interactive)
2688 (multi-isearch-files-regexp
2689 (dired-get-marked-files nil nil 'dired-nondirectory-p)))
2690
2691 ;;;###autoload
2692 (defun dired-do-search (regexp)
2693 "Search through all marked files for a match for REGEXP.
2694 Stops when a match is found.
2695 To continue searching for next match, use command \\[tags-loop-continue]."
2696 (interactive "sSearch marked files (regexp): ")
2697 (tags-search regexp '(dired-get-marked-files nil nil 'dired-nondirectory-p)))
2698
2699 ;;;###autoload
2700 (defun dired-do-query-replace-regexp (from to &optional delimited)
2701 "Do `query-replace-regexp' of FROM with TO, on all marked files.
2702 Third arg DELIMITED (prefix arg) means replace only word-delimited matches.
2703 If you exit (\\[keyboard-quit], RET or q), you can resume the query replace
2704 with the command \\[tags-loop-continue]."
2705 (interactive
2706 (let ((common
2707 (query-replace-read-args
2708 "Query replace regexp in marked files" t t)))
2709 (list (nth 0 common) (nth 1 common) (nth 2 common))))
2710 (dolist (file (dired-get-marked-files nil nil 'dired-nondirectory-p))
2711 (let ((buffer (get-file-buffer file)))
2712 (if (and buffer (with-current-buffer buffer
2713 buffer-read-only))
2714 (error "File `%s' is visited read-only" file))))
2715 (tags-query-replace from to delimited
2716 '(dired-get-marked-files nil nil 'dired-nondirectory-p)))
2717
2718 (declare-function xref--show-xrefs "xref")
2719 (declare-function xref-query-replace-in-results "xref")
2720
2721 ;;;###autoload
2722 (defun dired-do-find-regexp (regexp)
2723 "Find all matches for REGEXP in all marked files, recursively."
2724 (interactive "sSearch marked files (regexp): ")
2725 (require 'grep)
2726 (defvar grep-find-ignored-files)
2727 (let* ((files (dired-get-marked-files))
2728 (ignores (nconc (mapcar
2729 (lambda (s) (concat s "/"))
2730 vc-directory-exclusion-list)
2731 grep-find-ignored-files))
2732 (xrefs (cl-mapcan
2733 (lambda (file)
2734 (xref-collect-matches regexp "*" file
2735 (and (file-directory-p file)
2736 ignores)))
2737 files)))
2738 (unless xrefs
2739 (user-error "No matches for: %s" regexp))
2740 (xref--show-xrefs xrefs nil t)))
2741
2742 ;;;###autoload
2743 (defun dired-do-find-regexp-and-replace (from to)
2744 "Replace matches of FROM with TO, in all marked files, recursively."
2745 (interactive
2746 (let ((common
2747 (query-replace-read-args
2748 "Query replace regexp in marked files" t t)))
2749 (list (nth 0 common) (nth 1 common))))
2750 (with-current-buffer (dired-do-find-regexp from)
2751 (xref-query-replace-in-results from to)))
2752
2753 (defun dired-nondirectory-p (file)
2754 (not (file-directory-p file)))
2755 \f
2756 ;;;###autoload
2757 (defun dired-show-file-type (file &optional deref-symlinks)
2758 "Print the type of FILE, according to the `file' command.
2759 If you give a prefix to this command, and FILE is a symbolic
2760 link, then the type of the file linked to by FILE is printed
2761 instead."
2762 (interactive (list (dired-get-filename t) current-prefix-arg))
2763 (let (process-file-side-effects)
2764 (with-temp-buffer
2765 (if deref-symlinks
2766 (process-file "file" nil t t "-L" "--" file)
2767 (process-file "file" nil t t "--" file))
2768 (when (bolp)
2769 (backward-delete-char 1))
2770 (message "%s" (buffer-string)))))
2771
2772 (provide 'dired-aux)
2773
2774 ;; Local Variables:
2775 ;; byte-compile-dynamic: t
2776 ;; generated-autoload-file: "dired-loaddefs.el"
2777 ;; End:
2778
2779 ;;; dired-aux.el ends here