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