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