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