1 ;;; dired-aux.el --- less commonly used parts of dired
3 ;; Copyright (C) 1985-1986, 1992, 1994, 1998, 2000-2017 Free Software
6 ;; Author: Sebastian Kremer <sk@thp.uni-koeln.de>.
7 ;; Maintainer: emacs-devel@gnu.org
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/>.
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
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.
39 ;; We need macros in dired.el to compile properly,
40 ;; and we call subroutines in it too.
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.")
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]\\|$\\)")
54 (make-obsolete-variable 'dired-star-subst-regexp nil
"26.1")
55 (make-obsolete-variable 'dired-quark-subst-regexp nil
"26.1")
57 (defun dired-isolated-string-re (string)
58 "Return a regexp to match STRING isolated.
59 Isolated means that STRING is surrounded by spaces or at the beginning/end
60 of a string followed/prefixed with an space.
61 The regexp capture the preceding blank, STRING and the following blank as
62 the groups 1, 2 and 3 respectively."
63 (format "\\(\\`\\|[ \t]\\)\\(%s\\)\\([ \t]\\|\\'\\)" string
))
65 (defun dired--star-or-qmark-p (string match
&optional keep
)
66 "Return non-nil if STRING contains isolated MATCH or `\\=`?\\=`'.
67 MATCH should be the strings \"?\", `\\=`?\\=`', \"*\" or nil. The latter
68 means STRING contains either \"?\" or `\\=`?\\=`' or \"*\".
69 If optional arg KEEP is non-nil, then preserve the match data. Otherwise,
70 this function changes it and saves MATCH as the second match group.
72 Isolated means that MATCH is surrounded by spaces or at the beginning/end
73 of STRING followed/prefixed with an space. A match to `\\=`?\\=`',
74 isolated or not, is also valid."
75 (let ((regexps (list (dired-isolated-string-re (if match
(regexp-quote match
) "[*?]")))))
76 (when (or (null match
) (equal match
"?"))
77 (setq regexps
(append (list "\\(\\)\\(`\\?`\\)\\(\\)") regexps
)))
79 (funcall (if keep
#'string-match-p
#'string-match
) x string
))
83 (defun dired-diff (file &optional switches
)
84 "Compare file at point with FILE using `diff'.
85 If called interactively, prompt for FILE.
86 If the mark is active in Transient Mark mode, use the file at the mark
87 as the default for FILE. (That's the mark set by \\[set-mark-command],
88 not by Dired's \\[dired-mark] command.)
89 If the file at point has a backup file, use that as the default FILE.
90 If the file at point is a backup file, use its original, if that exists
91 and can be found. Note that customizations of `backup-directory-alist'
92 and `make-backup-file-name-function' change where this function searches
93 for the backup file, and affect its ability to find the original of a
96 FILE is the first argument given to the `diff' function. The file at
97 point is the second argument given to `diff'.
99 With prefix arg, prompt for second argument SWITCHES, which is
100 the string of command switches used as the third argument of `diff'."
102 (let* ((current (dired-get-filename t
))
103 ;; Get the latest existing backup file or its original.
104 (oldf (if (backup-file-name-p current
)
105 (file-name-sans-versions current
)
106 (diff-latest-backup-file current
)))
107 ;; Get the file at the mark.
108 (file-at-mark (if (and transient-mark-mode mark-active
)
109 (save-excursion (goto-char (mark t
))
110 (dired-get-filename t t
))))
111 (separate-dir (and oldf
112 (not (equal (file-name-directory oldf
)
113 (dired-current-directory)))))
114 (default-file (or file-at-mark
115 ;; If the file with which to compare
116 ;; doesn't exist, or we cannot intuit it,
117 ;; we forget that name and don't show it
118 ;; as the default, as an indication to the
119 ;; user that she should type the file
121 (and (if (and oldf
(file-readable-p oldf
)) oldf
)
124 (file-name-nondirectory oldf
)))))
125 ;; Use it as default if it's not the same as the current file,
126 ;; and the target dir is current or there is a default file.
127 (default (if (and (not (equal default-file current
))
128 (or (equal (dired-dwim-target-directory)
129 (dired-current-directory))
132 (target-dir (if default
134 (file-name-directory default
)
135 (dired-current-directory))
136 (dired-dwim-target-directory)))
137 (defaults (dired-dwim-target-defaults (list current
) target-dir
)))
139 (minibuffer-with-setup-hook
141 (set (make-local-variable 'minibuffer-default-add-function
) nil
)
142 (setq minibuffer-default defaults
))
144 (format "Diff %s with%s: " current
145 (if default
(format " (default %s)" default
) ""))
146 target-dir default t
))
147 (if current-prefix-arg
148 (read-string "Options for diff: "
149 (if (stringp diff-switches
)
151 (mapconcat 'identity diff-switches
" ")))))))
152 (let ((current (dired-get-filename t
)))
153 (when (or (equal (expand-file-name file
)
154 (expand-file-name current
))
155 (and (file-directory-p file
)
156 (equal (expand-file-name current file
)
157 (expand-file-name current
))))
158 (error "Attempt to compare the file to itself"))
159 (if (and (backup-file-name-p current
)
160 (equal file
(file-name-sans-versions current
)))
161 (diff current file switches
)
162 (diff file current switches
))))
165 (defun dired-backup-diff (&optional switches
)
166 "Diff this file with its backup file or vice versa.
167 Uses the latest backup, if there are several numerical backups.
168 If this file is a backup, diff it with its original.
169 The backup file is the first file given to `diff'.
170 With prefix arg, prompt for argument SWITCHES which is options for `diff'."
172 (if current-prefix-arg
173 (list (read-string "Options for diff: "
174 (if (stringp diff-switches
)
176 (mapconcat 'identity diff-switches
" "))))
178 (diff-backup (dired-get-filename) switches
))
181 (defun dired-compare-directories (dir2 predicate
)
182 "Mark files with different file attributes in two dired buffers.
183 Compare file attributes of files in the current directory
184 with file attributes in directory DIR2 using PREDICATE on pairs of files
185 with the same name. Mark files for which PREDICATE returns non-nil.
186 Mark files with different names if PREDICATE is nil (or interactively
187 with empty input at the predicate prompt).
189 PREDICATE is a Lisp expression that can refer to the following variables:
191 size1, size2 - file size in bytes
192 mtime1, mtime2 - last modification time in seconds, as a float
193 fa1, fa2 - list of file attributes
194 returned by function `file-attributes'
196 where 1 refers to attribute of file in the current dired buffer
197 and 2 to attribute of file in second dired buffer.
199 Examples of PREDICATE:
201 (> mtime1 mtime2) - mark newer files
202 (not (= size1 size2)) - mark files with different sizes
203 (not (string= (nth 8 fa1) (nth 8 fa2))) - mark files with different modes
204 (not (and (= (nth 2 fa1) (nth 2 fa2)) - mark files with different UID
205 (= (nth 3 fa1) (nth 3 fa2)))) and GID."
208 (let* ((target-dir (dired-dwim-target-directory))
209 (defaults (dired-dwim-target-defaults nil target-dir
)))
210 (minibuffer-with-setup-hook
212 (set (make-local-variable 'minibuffer-default-add-function
) nil
)
213 (setq minibuffer-default defaults
))
214 (read-directory-name (format "Compare %s with: "
215 (dired-current-directory))
216 target-dir target-dir t
)))
217 (read-from-minibuffer "Mark if (lisp expr or RET): " nil nil t nil
"nil")))
218 (let* ((dir1 (dired-current-directory))
219 (file-alist1 (dired-files-attributes dir1
))
220 (file-alist2 (dired-files-attributes dir2
))
221 file-list1 file-list2
)
222 (setq file-alist1
(delq (assoc "." file-alist1
) file-alist1
))
223 (setq file-alist1
(delq (assoc ".." file-alist1
) file-alist1
))
224 (setq file-alist2
(delq (assoc "." file-alist2
) file-alist2
))
225 (setq file-alist2
(delq (assoc ".." file-alist2
) file-alist2
))
226 (setq file-list1
(mapcar
228 (dired-file-set-difference
229 file-alist1 file-alist2
233 (dired-file-set-difference
234 file-alist2 file-alist1
236 (dired-fun-in-all-buffers
240 (member (dired-get-filename nil t
) file-list1
) nil
)))
241 (dired-fun-in-all-buffers
245 (member (dired-get-filename nil t
) file-list2
) nil
)))
246 (message "Marked in dir1: %s files, in dir2: %s files"
248 (length file-list2
))))
250 (defun dired-file-set-difference (list1 list2 predicate
)
251 "Combine LIST1 and LIST2 using a set-difference operation.
252 The result list contains all file items that appear in LIST1 but not LIST2.
253 This is a non-destructive function; it makes a copy of the data if necessary
254 to avoid corrupting the original LIST1 and LIST2.
255 PREDICATE (see `dired-compare-directories') is an additional match
256 condition. Two file items are considered to match if they are equal
257 *and* PREDICATE evaluates to t."
258 (if (or (null list1
) (null list2
))
261 (dolist (file1 list1
)
262 (unless (let ((list list2
))
264 (let* ((file2 (car list
))
265 (fa1 (car (cddr file1
)))
266 (fa2 (car (cddr file2
))))
268 (not (equal (car file1
) (car file2
)))
272 (size1 .
,(nth 7 fa1
))
273 (size2 .
,(nth 7 fa2
))
275 .
,(float-time (nth 5 fa1
)))
277 .
,(float-time (nth 5 fa2
)))
279 (setq list
(cdr list
)))
284 (defun dired-files-attributes (dir)
285 "Return a list of all file names and attributes from DIR.
286 List has a form of (file-name full-file-name (attribute-list))."
289 (let ((full-file-name (expand-file-name file-name dir
)))
292 (file-attributes full-file-name
))))
293 (directory-files dir
)))
295 ;;; Change file attributes
297 (defun dired-do-chxxx (attribute-name program op-symbol arg
)
298 ;; Change file attributes (group, owner, timestamp) of marked files and
299 ;; refresh their file lines.
300 ;; ATTRIBUTE-NAME is a string describing the attribute to the user.
301 ;; PROGRAM is the program used to change the attribute.
302 ;; OP-SYMBOL is the type of operation (for use in `dired-mark-pop-up').
303 ;; ARG describes which files to use, as in `dired-get-marked-files'.
304 (let* ((files (dired-get-marked-files t arg
))
305 ;; The source of default file attributes is the file at point.
306 (default-file (dired-get-filename t t
))
307 (default (when default-file
308 (cond ((eq op-symbol
'touch
)
311 (nth 5 (file-attributes default-file
))))
312 ((eq op-symbol
'chown
)
313 (nth 2 (file-attributes default-file
'string
)))
314 ((eq op-symbol
'chgrp
)
315 (nth 3 (file-attributes default-file
'string
))))))
316 (prompt (concat "Change " attribute-name
" of %s to"
317 (if (eq op-symbol
'touch
)
320 (new-attribute (dired-mark-read-string prompt nil op-symbol
322 (cond ((eq op-symbol
'chown
)
324 ((eq op-symbol
'chgrp
)
326 (operation (concat program
" " new-attribute
))
327 ;; When file-name-coding-system is set to something different
328 ;; from locale-coding-system, leaving the encoding
329 ;; determination to call-process will do the wrong thing,
330 ;; because the arguments in this case are file names, not
331 ;; just some arbitrary text. (This must be bound last, to
332 ;; avoid adverse effects on any of the preceding forms.)
333 (coding-system-for-write (or file-name-coding-system
334 default-file-name-coding-system
))
337 (dired-bunch-files 10000
338 #'dired-check-process
340 (list operation program
)
341 (unless (or (string-equal new-attribute
"")
342 ;; Use `eq' instead of `equal'
343 ;; to detect empty input (bug#12399).
344 (eq new-attribute default
))
345 (if (eq op-symbol
'touch
)
346 (list "-t" new-attribute
)
347 (list new-attribute
)))
348 (if (string-match-p "gnu" system-configuration
)
351 (dired-do-redisplay arg
);; moves point if ARG is an integer
354 (format "%s: error" operation
)
358 (defun dired-do-chmod (&optional arg
)
359 "Change the mode of the marked (or next ARG) files.
360 Symbolic modes like `g+w' are allowed.
361 Type M-n to pull the file attributes of the file at point
362 into the minibuffer."
364 (let* ((files (dired-get-marked-files t arg
))
365 ;; The source of default file attributes is the file at point.
366 (default-file (dired-get-filename t t
))
367 (modestr (when default-file
368 (nth 8 (file-attributes default-file
))))
370 (and (stringp modestr
)
371 (string-match "^.\\(...\\)\\(...\\)\\(...\\)$" modestr
)
372 (replace-regexp-in-string
374 (format "u=%s,g=%s,o=%s"
375 (match-string 1 modestr
)
376 (match-string 2 modestr
)
377 (match-string 3 modestr
)))))
378 (modes (dired-mark-read-string
379 "Change mode of %s to: "
380 nil
'chmod arg files default
))
382 (cond ((or (equal modes
"")
383 ;; Use `eq' instead of `equal'
384 ;; to detect empty input (bug#12399).
386 ;; We used to treat empty input as DEFAULT, but that is not
387 ;; such a good idea (Bug#9361).
388 (error "No file mode specified"))
389 ((string-match-p "^[0-7]+" modes
)
390 (setq num-modes
(string-to-number modes
8))))
395 (if num-modes num-modes
396 (file-modes-symbolic-to-number modes
(file-modes file
)))))
397 (dired-do-redisplay arg
)))
400 (defun dired-do-chgrp (&optional arg
)
401 "Change the group of the marked (or next ARG) files.
402 Type M-n to pull the file attributes of the file at point
403 into the minibuffer."
405 (if (memq system-type
'(ms-dos windows-nt
))
406 (error "chgrp not supported on this system"))
407 (dired-do-chxxx "Group" "chgrp" 'chgrp arg
))
410 (defun dired-do-chown (&optional arg
)
411 "Change the owner of the marked (or next ARG) files.
412 Type M-n to pull the file attributes of the file at point
413 into the minibuffer."
415 (if (memq system-type
'(ms-dos windows-nt
))
416 (error "chown not supported on this system"))
417 (dired-do-chxxx "Owner" dired-chown-program
'chown arg
))
420 (defun dired-do-touch (&optional arg
)
421 "Change the timestamp of the marked (or next ARG) files.
423 Type M-n to pull the file attributes of the file at point
424 into the minibuffer."
426 (dired-do-chxxx "Timestamp" dired-touch-program
'touch arg
))
428 ;; Process all the files in FILES in batches of a convenient size,
429 ;; by means of (FUNCALL FUNCTION ARGS... SOME-FILES...).
430 ;; Batches are chosen to need less than MAX chars for the file names,
431 ;; allowing 3 extra characters of separator per file name.
432 (defun dired-bunch-files (max function args files
)
437 ;; Accumulate files as long as they fit in MAX chars,
438 ;; then process the ones accumulated so far.
440 (let* ((thisfile (car files
))
441 (thislength (+ (length thisfile
) 3))
443 ;; If we have at least 1 pending file
444 ;; and this file won't fit in the length limit, process now.
445 (if (and pending
(> (+ thislength pending-length
) max
))
446 (setq pending
(nreverse pending
)
447 ;; The elements of PENDING are now in forward order.
448 ;; Do the operation and record failures.
449 failures
(nconc (apply function
(append args pending
))
451 ;; Transfer the elements of PENDING onto PAST
452 ;; and clear it out. Now PAST contains the first N files
453 ;; specified (for some N), and FILES contains the rest.
454 past
(nconc past pending
)
457 ;; Do (setq pending (cons thisfile pending))
458 ;; but reuse the cons that was in `files'.
459 (setcdr files pending
)
461 (setq pending-length
(+ thislength pending-length
))
463 (setq pending
(nreverse pending
))
465 (nconc (apply function
(append args pending
))
467 ;; Now the original list FILES has been put back as it was.
468 (nconc past pending
))))
470 (defvar lpr-printer-switch
)
473 (defun dired-do-print (&optional arg
)
474 "Print the marked (or next ARG) files.
475 Uses the shell command coming from variables `lpr-command' and
476 `lpr-switches' as default."
479 (let* ((file-list (dired-get-marked-files t arg
))
481 (if (and (stringp printer-name
)
482 (string< "" printer-name
))
483 (cons (concat lpr-printer-switch printer-name
)
486 (command (dired-mark-read-string
490 (if (stringp lpr-switches
)
494 'print arg file-list
)))
495 (dired-run-shell-command (dired-shell-stuff-it command file-list nil
))))
497 (defun dired-mark-read-string (prompt initial op-symbol arg files
498 &optional default-value collection
)
499 "Read args for a Dired marked-files command, prompting with PROMPT.
500 Return the user input (a string).
502 INITIAL, if non-nil, is the initial minibuffer input.
503 OP-SYMBOL is an operation symbol (see `dired-no-confirm').
504 ARG is normally the prefix argument for the calling command;
505 it is passed as the first argument to `dired-mark-prompt'.
506 FILES should be a list of marked files' names.
508 Optional arg DEFAULT-VALUE is a default value or list of default
509 values, passed as the seventh arg to `completing-read'.
511 Optional arg COLLECTION is a collection of possible completions,
512 passed as the second arg to `completing-read'."
513 (dired-mark-pop-up nil op-symbol files
515 (format prompt
(dired-mark-prompt arg files
))
516 collection nil nil initial nil default-value nil
))
518 ;;; Cleaning a directory: flagging some backups for deletion.
520 (defvar dired-file-version-alist
)
523 (defun dired-clean-directory (keep)
524 "Flag numerical backups for deletion.
525 Spares `dired-kept-versions' latest versions, and `kept-old-versions' oldest.
526 Positive prefix arg KEEP overrides `dired-kept-versions';
527 Negative prefix arg KEEP overrides `kept-old-versions' with KEEP made positive.
529 To clear the flags on these files, you can use \\[dired-flag-backup-files]
530 with a prefix argument."
532 (setq keep
(if keep
(prefix-numeric-value keep
) dired-kept-versions
))
533 (let ((early-retention (if (< keep
0) (- keep
) kept-old-versions
))
534 (late-retention (if (<= keep
0) dired-kept-versions keep
))
535 (dired-file-version-alist ()))
536 (message "Cleaning numerical backups (keeping %d late, %d old)..."
537 late-retention early-retention
)
538 ;; Look at each file.
539 ;; If the file has numeric backup versions,
540 ;; put on dired-file-version-alist an element of the form
541 ;; (FILENAME . VERSION-NUMBER-LIST)
542 (dired-map-dired-file-lines #'dired-collect-file-versions
)
543 ;; Sort each VERSION-NUMBER-LIST,
544 ;; and remove the versions not to be deleted.
545 (let ((fval dired-file-version-alist
))
547 (let* ((sorted-v-list (cons 'q
(sort (cdr (car fval
)) '<)))
548 (v-count (length sorted-v-list
)))
549 (if (> v-count
(+ early-retention late-retention
))
550 (rplacd (nthcdr early-retention sorted-v-list
)
551 (nthcdr (- v-count late-retention
)
554 (cdr sorted-v-list
)))
555 (setq fval
(cdr fval
))))
556 ;; Look at each file. If it is a numeric backup file,
557 ;; find it in a VERSION-NUMBER-LIST and maybe flag it for deletion.
558 (dired-map-dired-file-lines #'dired-trample-file-versions
)
559 (message "Cleaning numerical backups...done")))
561 ;;; Subroutines of dired-clean-directory.
563 (defun dired-map-dired-file-lines (fun)
564 ;; Perform FUN with point at the end of each non-directory line.
565 ;; FUN takes one argument, the absolute filename.
567 (let (file buffer-read-only
)
568 (goto-char (point-min))
571 (and (not (looking-at-p dired-re-dir
))
573 (setq file
(dired-get-filename nil t
)) ; nil on non-file
575 (funcall fun file
))))
578 (defvar backup-extract-version-start
) ; used in backup-extract-version
580 (defun dired-collect-file-versions (fn)
581 (let ((fn (file-name-sans-versions fn
)))
582 ;; Only do work if this file is not already in the alist.
583 (if (assoc fn dired-file-version-alist
)
585 ;; If it looks like file FN has versions, return a list of the versions.
586 ;;That is a list of strings which are file names.
587 ;;The caller may want to flag some of these files for deletion.
588 (let* ((base-versions
589 (concat (file-name-nondirectory fn
) ".~"))
590 (backup-extract-version-start (length base-versions
))
591 (possibilities (file-name-all-completions
593 (file-name-directory fn
)))
594 (versions (mapcar 'backup-extract-version possibilities
)))
596 (setq dired-file-version-alist
597 (cons (cons fn versions
)
598 dired-file-version-alist
)))))))
600 (defun dired-trample-file-versions (fn)
601 (let* ((start-vn (string-match-p "\\.~[0-9]+~$" fn
))
604 (setq base-version-list
; there was a base version to which
605 (assoc (substring fn
0 start-vn
) ; this looks like a
606 dired-file-version-alist
)) ; subversion
607 (not (memq (string-to-number (substring fn
(+ 2 start-vn
)))
608 base-version-list
)) ; this one doesn't make the cut
609 (progn (beginning-of-line)
611 (insert dired-del-marker
)))))
615 (declare-function mailcap-file-default-commands
"mailcap" (files))
617 (defun minibuffer-default-add-dired-shell-commands ()
618 "Return a list of all commands associated with current dired files.
619 This function is used to add all related commands retrieved by `mailcap'
620 to the end of the list of defaults just after the default value."
622 (let ((commands (and (boundp 'files
) (require 'mailcap nil t
)
623 (mailcap-file-default-commands files
))))
624 (if (listp minibuffer-default
)
625 (append minibuffer-default commands
)
626 (cons minibuffer-default commands
))))
628 ;; This is an extra function so that you can redefine it, e.g., to use gmhist.
629 (defun dired-read-shell-command (prompt arg files
)
630 "Read a dired shell command.
631 PROMPT should be a format string with one \"%s\" format sequence,
632 which is replaced by the value returned by `dired-mark-prompt',
633 with ARG and FILES as its arguments. FILES should be a list of
634 file names. The result is used as the prompt.
636 This normally reads using `read-shell-command', but if the
637 `dired-x' package is loaded, use `dired-guess-shell-command' to
638 offer a smarter default choice of shell command."
639 (minibuffer-with-setup-hook
641 (set (make-local-variable 'minibuffer-default-add-function
)
642 'minibuffer-default-add-dired-shell-commands
))
643 (setq prompt
(format prompt
(dired-mark-prompt arg files
)))
644 (if (functionp 'dired-guess-shell-command
)
645 (dired-mark-pop-up nil
'shell files
646 'dired-guess-shell-command prompt files
)
647 (dired-mark-pop-up nil
'shell files
648 'read-shell-command prompt nil nil
))))
651 (defun dired-do-async-shell-command (command &optional arg file-list
)
652 "Run a shell command COMMAND on the marked files asynchronously.
654 Like `dired-do-shell-command', but adds `&' at the end of COMMAND
655 to execute it asynchronously.
657 When operating on multiple files, asynchronous commands
658 are executed in the background on each file in parallel.
659 In shell syntax this means separating the individual commands
660 with `&'. However, when COMMAND ends in `;' or `;&' then commands
661 are executed in the background on each file sequentially waiting
662 for each command to terminate before running the next command.
663 In shell syntax this means separating the individual commands with `;'.
665 The output appears in the buffer `*Async Shell Command*'."
667 (let ((files (dired-get-marked-files t current-prefix-arg
)))
669 ;; Want to give feedback whether this file or marked files are used:
670 (dired-read-shell-command "& on %s: " current-prefix-arg files
)
673 (unless (string-match-p "&[ \t]*\\'" command
)
674 (setq command
(concat command
" &")))
675 (dired-do-shell-command command arg file-list
))
678 (defun dired-do-shell-command (command &optional arg file-list
)
679 "Run a shell command COMMAND on the marked files.
680 If no files are marked or a numeric prefix arg is given,
681 the next ARG files are used. Just \\[universal-argument] means the current file.
682 The prompt mentions the file(s) or the marker, as appropriate.
684 If there is a `*' in COMMAND, surrounded by whitespace, this runs
685 COMMAND just once with the entire file list substituted there.
687 If there is no `*', but there is a `?' in COMMAND, surrounded by
688 whitespace, or a `\\=`?\\=`' this runs COMMAND on each file
689 individually with the file name substituted for `?' or `\\=`?\\=`'.
691 Otherwise, this runs COMMAND on each file individually with the
692 file name added at the end of COMMAND (separated by a space).
694 `*' and `?' when not surrounded by whitespace nor `\\=`' have no special
695 significance for `dired-do-shell-command', and are passed through
696 normally to the shell, but you must confirm first.
698 If you want to use `*' as a shell wildcard with whitespace around
699 it, write `*\"\"' in place of just `*'. This is equivalent to just
700 `*' in the shell, but avoids Dired's special handling.
702 If COMMAND ends in `&', `;', or `;&', it is executed in the
703 background asynchronously, and the output appears in the buffer
704 `*Async Shell Command*'. When operating on multiple files and COMMAND
705 ends in `&', the shell command is executed on each file in parallel.
706 However, when COMMAND ends in `;' or `;&' then commands are executed
707 in the background on each file sequentially waiting for each command
708 to terminate before running the next command. You can also use
709 `dired-do-async-shell-command' that automatically adds `&'.
711 Otherwise, COMMAND is executed synchronously, and the output
712 appears in the buffer `*Shell Command Output*'.
714 This feature does not try to redisplay Dired buffers afterward, as
715 there's no telling what files COMMAND may have changed.
716 Type \\[dired-do-redisplay] to redisplay the marked files.
718 When COMMAND runs, its working directory is the top-level directory
719 of the Dired buffer, so output files usually are created there
720 instead of in a subdir.
722 In a noninteractive call (from Lisp code), you must specify
723 the list of file names explicitly with the FILE-LIST argument, which
724 can be produced by `dired-get-marked-files', for example."
725 ;;Functions dired-run-shell-command and dired-shell-stuff-it do the
726 ;;actual work and can be redefined for customization.
728 (let ((files (dired-get-marked-files t current-prefix-arg
)))
730 ;; Want to give feedback whether this file or marked files are used:
731 (dired-read-shell-command "! on %s: " current-prefix-arg files
)
734 (cl-flet ((need-confirm-p
737 (regexp (regexp-quote str
)))
738 ;; Drop all ? and * surrounded by spaces and `?`.
739 (while (and (string-match regexp res
)
740 (dired--star-or-qmark-p res str
))
741 (setq res
(replace-match "" t t res
0)))
742 (string-match regexp res
))))
743 (let* ((on-each (not (dired--star-or-qmark-p command
"*" 'keep
)))
744 (no-subst (not (dired--star-or-qmark-p command
"?" 'keep
)))
745 (star (string-match "\\*" command
))
746 (qmark (string-match "\\?" command
))
747 ;; Get confirmation for wildcards that may have been meant
748 ;; to control substitution of a file name or the file name list.
749 (ok (cond ((not (or on-each no-subst
))
750 (error "You can not combine `*' and `?' substitution marks"))
751 ((need-confirm-p command
"*")
752 (y-or-n-p (format-message
753 "Confirm--do you mean to use `*' as a wildcard? ")))
754 ((need-confirm-p command
"?")
755 (y-or-n-p (format-message
756 "Confirm--do you mean to use `?' as a wildcard? ")))
760 (dired-bunch-files (- 10000 (length command
))
761 (lambda (&rest files
)
762 (dired-run-shell-command
763 (dired-shell-stuff-it command files t arg
)))
765 ;; execute the shell command
766 (dired-run-shell-command
767 (dired-shell-stuff-it command file-list nil arg
)))))))
769 ;; Might use {,} for bash or csh:
770 (defvar dired-mark-prefix
""
771 "Prepended to marked files in dired shell commands.")
772 (defvar dired-mark-postfix
""
773 "Appended to marked files in dired shell commands.")
774 (defvar dired-mark-separator
" "
775 "Separates marked files in dired shell commands.")
777 (defun dired-shell-stuff-it (command file-list on-each
&optional _raw-arg
)
778 ;; "Make up a shell command line from COMMAND and FILE-LIST.
779 ;; If ON-EACH is t, COMMAND should be applied to each file, else
780 ;; simply concat all files and apply COMMAND to this.
781 ;; FILE-LIST's elements will be quoted for the shell."
782 ;; Might be redefined for smarter things and could then use RAW-ARG
783 ;; (coming from interactive P and currently ignored) to decide what to do.
784 ;; Smart would be a way to access basename or extension of file names.
785 (let* ((in-background (string-match "[ \t]*&[ \t]*\\'" command
))
786 (command (if in-background
787 (substring command
0 (match-beginning 0))
789 (sequentially (string-match "[ \t]*;[ \t]*\\'" command
))
790 (command (if sequentially
791 (substring command
0 (match-beginning 0))
793 (parallel-in-background
794 (and in-background
(not sequentially
) (not (eq system-type
'ms-dos
))))
795 (w32-shell (and (fboundp 'w32-shell-dos-semantics
)
796 (w32-shell-dos-semantics)))
797 ;; The way to run a command in background in Windows shells
798 ;; is to use the START command. The /B switch means not to
799 ;; create a new window for the command.
800 (cmd-prefix (if w32-shell
"start /b " ""))
801 ;; Windows shells don't support chaining with ";", they use
803 (cmd-sep (if (and (not w32-shell
) (not parallel-in-background
))
807 (if (dired--star-or-qmark-p command nil
'keep
)
809 (let ((retval (concat cmd-prefix command
)))
810 (while (dired--star-or-qmark-p retval nil
)
811 (setq retval
(replace-match x t t retval
2)))
813 (lambda (x) (concat cmd-prefix command dired-mark-separator x
)))))
817 (mapconcat stuff-it
(mapcar 'shell-quote-argument file-list
)
819 ;; POSIX shells running a list of commands in the background
820 ;; (LIST = cmd_1 & [cmd_2 & ... cmd_i & ... cmd_N &])
821 ;; return once cmd_N ends, i.e., the shell does not
822 ;; wait for cmd_i to finish before executing cmd_i+1.
823 ;; That means, running (shell-command LIST) may not show
824 ;; the output of all the commands (Bug#23206).
825 ;; Add 'wait' to force those POSIX shells to wait until
826 ;; all commands finish.
827 (or (and parallel-in-background
(not w32-shell
)
831 (let ((files (mapconcat 'shell-quote-argument
832 file-list dired-mark-separator
)))
833 (when (cdr file-list
)
834 (setq files
(concat dired-mark-prefix files dired-mark-postfix
)))
835 (funcall stuff-it files
))))
836 (or (and in-background
"&") ""))))
838 ;; This is an extra function so that it can be redefined by ange-ftp.
840 (defun dired-run-shell-command (command)
842 (find-file-name-handler (directory-file-name default-directory
)
844 (if handler
(apply handler
'shell-command
(list command
))
845 (shell-command command
)))
846 ;; Return nil for sake of nconc in dired-bunch-files.
850 (defun dired-check-process (msg program
&rest arguments
)
851 "Display MSG while running PROGRAM, and check for output.
852 Remaining arguments are strings passed as command arguments to PROGRAM.
853 On error, insert output
854 in a log buffer and return the offending ARGUMENTS or PROGRAM.
855 Caller can cons up a list of failed args.
856 Else returns nil for success."
857 (let (err-buffer err
(dir default-directory
))
858 (message "%s..." msg
)
860 ;; Get a clean buffer for error output:
861 (setq err-buffer
(get-buffer-create " *dired-check-process output*"))
862 (set-buffer err-buffer
)
864 (setq default-directory dir
; caller's default-directory
865 err
(not (eq 0 (apply 'process-file program nil t nil arguments
))))
868 (dired-log (concat program
" " (prin1-to-string arguments
) "\n"))
869 (dired-log err-buffer
)
870 (or arguments program t
))
871 (kill-buffer err-buffer
)
872 (message "%s...done" msg
)
875 (defun dired-shell-command (cmd)
876 "Run CMD, and check for output.
877 On error, pop up the log buffer.
878 Return the result of `process-file' - zero for success."
879 (let ((out-buffer " *dired-check-process output*")
880 (dir default-directory
))
881 (with-current-buffer (get-buffer-create out-buffer
)
883 (let* ((default-directory dir
)
892 (pop-to-buffer out-buffer
))
895 ;; Commands that delete or redisplay part of the dired buffer.
897 (defun dired-kill-line (&optional arg
)
898 "Kill the current line (not the files).
899 With a prefix argument, kill that many lines starting with the current line.
900 \(A negative argument kills backward.)"
902 (setq arg
(prefix-numeric-value arg
))
903 (let (buffer-read-only file
)
905 (setq file
(dired-get-filename nil t
))
907 (error "Can only kill file lines")
908 (save-excursion (and file
909 (dired-goto-subdir file
)
910 (dired-kill-subdir)))
911 (delete-region (line-beginning-position)
912 (progn (forward-line 1) (point)))
917 (dired-move-to-filename)))
920 (defun dired-do-kill-lines (&optional arg fmt
)
921 "Kill all marked lines (not the files).
922 With a prefix argument, kill that many lines starting with the current line.
923 \(A negative argument kills backward.)
924 If you use this command with a prefix argument to kill the line
925 for a file that is a directory, which you have inserted in the
926 Dired buffer as a subdirectory, then it deletes that subdirectory
927 from the buffer as well.
928 To kill an entire subdirectory \(without killing its line in the
929 parent directory), go to its directory header line and use this
930 command with a prefix argument (the value does not matter)."
931 ;; Returns count of killed lines. FMT="" suppresses message.
934 (if (dired-get-subdir)
936 (dired-kill-line arg
))
938 (goto-char (point-min))
939 (let (buffer-read-only
941 (regexp (dired-marker-regexp)))
942 (while (and (not (eobp))
943 (re-search-forward regexp nil t
))
944 (setq count
(1+ count
))
945 (delete-region (line-beginning-position)
946 (progn (forward-line 1) (point))))
948 (message (or fmt
"Killed %d line%s.") count
(dired-plural-s count
)))
951 ;;;###end dired-cmd.el
954 ;;;###begin dired-cp.el
956 (defun dired-compress ()
957 ;; Compress or uncompress the current file.
958 ;; Return nil for success, offending filename else.
959 (let* (buffer-read-only
960 (from-file (dired-get-filename))
961 (new-file (dired-compress-file from-file
)))
963 (let ((start (point)))
964 ;; Remove any preexisting entry for the name NEW-FILE.
965 (ignore-errors (dired-remove-entry new-file
))
967 ;; Now replace the current line with an entry for NEW-FILE.
968 (dired-update-file-line new-file
) nil
)
969 (dired-log (concat "Failed to compress" from-file
))
972 (defvar dired-compress-file-suffixes
974 ;; "tar -zxf" isn't used because it's not available on the
975 ;; Solaris10 version of tar. Solaris10 becomes obsolete in 2021.
976 ;; Same thing on AIX 7.1.
977 ("\\.tar\\.gz\\'" "" "gzip -dc %i | tar -xv")
978 ("\\.tgz\\'" "" "gzip -dc %i | tar -xv")
979 ("\\.gz\\'" "" "gunzip")
980 ("\\.Z\\'" "" "uncompress")
981 ;; For .z, try gunzip. It might be an old gzip file,
982 ;; or it might be from compact? pack? (which?) but gunzip handles both.
983 ("\\.z\\'" "" "gunzip")
984 ("\\.dz\\'" "" "dictunzip")
985 ("\\.tbz\\'" ".tar" "bunzip2")
986 ("\\.bz2\\'" "" "bunzip2")
987 ("\\.xz\\'" "" "unxz")
988 ("\\.zip\\'" "" "unzip -o -d %o %i")
989 ("\\.7z\\'" "" "7z x -aoa -o%o %i")
990 ;; This item controls naming for compression.
991 ("\\.tar\\'" ".tgz" nil
)
992 ;; This item controls the compression of directories
993 (":" ".tar.gz" "tar -c %i | gzip -c9 > %o"))
994 "Control changes in file name suffixes for compression and uncompression.
995 Each element specifies one transformation rule, and has the form:
996 (REGEXP NEW-SUFFIX PROGRAM)
997 The rule applies when the old file name matches REGEXP.
998 The new file name is computed by deleting the part that matches REGEXP
999 (as well as anything after that), then adding NEW-SUFFIX in its place.
1000 If PROGRAM is non-nil, the rule is an uncompression rule,
1001 and uncompression is done by running PROGRAM.
1003 Within PROGRAM, %i denotes the input file, and %o denotes the
1006 Otherwise, the rule is a compression rule, and compression is done with gzip.
1007 ARGS are command switches passed to PROGRAM.")
1009 (defvar dired-compress-files-alist
1010 '(("\\.tar\\.gz\\'" .
"tar -c %i | gzip -c9 > %o")
1011 ("\\.tar\\.bz2\\'" .
"tar -c %i | bzip2 -c9 > %o")
1012 ("\\.tar\\.xz\\'" .
"tar -c %i | xz -c9 > %o")
1013 ("\\.zip\\'" .
"zip %o -r --filesync %i"))
1014 "Control the compression shell command for `dired-do-compress-to'.
1016 Each element is (REGEXP . CMD), where REGEXP is the name of the
1017 archive to which you want to compress, and CMD the the
1018 corresponding command.
1020 Within CMD, %i denotes the input file(s), and %o denotes the
1021 output file. %i path(s) are relative, while %o is absolute.")
1023 (declare-function format-spec
"format-spec.el" (format specification
))
1026 (defun dired-do-compress-to ()
1027 "Compress selected files and directories to an archive.
1028 Prompt for the archive file name.
1029 Choose the archiving command based on the archive file-name extension
1030 and `dired-compress-files-alist'."
1032 (let* ((in-files (dired-get-marked-files))
1033 (out-file (expand-file-name (read-file-name "Compress to: ")))
1036 (string-match (car x
) out-file
))
1037 dired-compress-files-alist
)))
1040 "No compression rule found for %s, see `dired-compress-files-alist'"
1042 ((and (file-exists-p out-file
)
1044 (format "%s exists, overwrite?"
1045 (abbreviate-file-name out-file
)))))
1046 (message "Compression aborted"))
1049 (dired-shell-command
1050 (format-spec (cdr rule
)
1051 `((?\o .
,(shell-quote-argument out-file
))
1054 (shell-quote-argument (file-name-nondirectory
1057 (message "Compressed %d file(s) to %s"
1059 (file-name-nondirectory out-file
)))))))
1062 (defun dired-compress-file (file)
1063 "Compress or uncompress FILE.
1064 Return the name of the compressed or uncompressed file.
1065 Return nil if no change in files."
1066 (let ((handler (find-file-name-handler file
'dired-compress-file
))
1068 (suffixes dired-compress-file-suffixes
)
1070 ;; See if any suffix rule matches this file name.
1072 (let (case-fold-search)
1073 (if (string-match (car (car suffixes
)) file
)
1074 (setq suffix
(car suffixes
) suffixes nil
))
1075 (setq suffixes
(cdr suffixes
))))
1076 ;; If so, compute desired new name.
1078 (setq newname
(concat (substring file
0 (match-beginning 0))
1081 (funcall handler
'dired-compress-file file
))
1082 ((file-symlink-p file
)
1084 ((and suffix
(setq command
(nth 2 suffix
)))
1085 (if (string-match "%[io]" command
)
1086 (prog1 (setq newname
(file-name-as-directory newname
))
1087 (dired-shell-command
1088 (replace-regexp-in-string
1089 "%o" (shell-quote-argument newname
)
1090 (replace-regexp-in-string
1091 "%i" (shell-quote-argument file
)
1095 ;; We found an uncompression rule.
1097 (dired-check-process
1098 (concat "Uncompressing " file
)
1103 ;; We don't recognize the file as compressed, so compress it.
1104 ;; Try gzip; if we don't have that, use compress.
1106 (if (file-directory-p file
)
1108 (setq suffix
(cdr (assoc ":" dired-compress-file-suffixes
)))
1110 (let ((out-name (concat file
(car suffix
)))
1111 (default-directory (file-name-directory file
)))
1112 (dired-shell-command
1113 (replace-regexp-in-string
1114 "%o" (shell-quote-argument out-name
)
1115 (replace-regexp-in-string
1116 "%i" (shell-quote-argument (file-name-nondirectory file
))
1121 (let ((out-name (concat file
".gz")))
1122 (and (or (not (file-exists-p out-name
))
1124 (format "File %s already exists. Really compress? "
1127 (dired-check-process (concat "Compressing " file
)
1129 (or (file-exists-p out-name
)
1130 (setq out-name
(concat file
".z")))
1131 ;; Rename the compressed file to NEWNAME
1132 ;; if it hasn't got that name already.
1133 (if (and newname
(not (equal newname out-name
)))
1135 (rename-file out-name newname t
)
1139 (if (not (dired-check-process (concat "Compressing " file
)
1140 "compress" "-f" file
))
1141 ;; Don't use NEWNAME with `compress'.
1142 (concat file
".Z"))))))))
1144 (defun dired-mark-confirm (op-symbol arg
)
1145 ;; Request confirmation from the user that the operation described
1146 ;; by OP-SYMBOL is to be performed on the marked files.
1147 ;; Confirmation consists in a y-or-n question with a file list
1148 ;; pop-up unless OP-SYMBOL is a member of `dired-no-confirm'.
1149 ;; The files used are determined by ARG (as in dired-get-marked-files).
1150 (or (eq dired-no-confirm t
)
1151 (memq op-symbol dired-no-confirm
)
1152 ;; Pass t for DISTINGUISH-ONE-MARKED so that a single file which
1153 ;; is marked pops up a window. That will help the user see
1154 ;; it isn't the current line file.
1155 (let ((files (dired-get-marked-files t arg nil t
))
1156 (string (if (eq op-symbol
'compress
) "Compress or uncompress"
1157 (capitalize (symbol-name op-symbol
)))))
1158 (dired-mark-pop-up nil op-symbol files
#'y-or-n-p
1160 (dired-mark-prompt arg files
) "? ")))))
1162 (defun dired-map-over-marks-check (fun arg op-symbol
&optional show-progress
)
1163 ; "Map FUN over marked files (with second ARG like in dired-map-over-marks)
1164 ; and display failures.
1166 ; FUN takes zero args. It returns non-nil (the offending object, e.g.
1167 ; the short form of the filename) for a failure and probably logs a
1168 ; detailed error explanation using function `dired-log'.
1170 ; OP-SYMBOL is a symbol describing the operation performed (e.g.
1171 ; `compress'). It is used with `dired-mark-pop-up' to prompt the user
1172 ; (e.g. with `Compress * [2 files]? ') and to display errors (e.g.
1173 ; `Failed to compress 1 of 2 files - type W to see why ("foo")')
1175 ; SHOW-PROGRESS if non-nil means redisplay dired after each file."
1176 (if (dired-mark-confirm op-symbol arg
)
1177 (let* ((total-list;; all of FUN's return values
1178 (dired-map-over-marks (funcall fun
) arg show-progress
))
1179 (total (length total-list
))
1180 (failures (delq nil total-list
))
1181 (count (length failures
))
1182 (string (if (eq op-symbol
'compress
) "Compress or uncompress"
1183 (capitalize (symbol-name op-symbol
)))))
1185 (message "%s: %d file%s."
1186 string total
(dired-plural-s total
))
1187 ;; end this bunch of errors:
1189 (format "Failed to %s %d of %d file%s"
1190 (downcase string
) count total
(dired-plural-s total
))
1194 (defun dired-query (sym prompt
&rest args
)
1195 "Format PROMPT with ARGS, query user, and store the result in SYM.
1196 The return value is either nil or t.
1198 The user may type y or SPC to accept once; n or DEL to skip once;
1199 ! to accept this and subsequent queries; or q or ESC to decline
1200 this and subsequent queries.
1202 If SYM is already bound to a non-nil value, this function may
1203 return automatically without querying the user. If SYM is !,
1204 return t; if SYM is q or ESC, return nil."
1205 (let* ((char (symbol-value sym
))
1206 (char-choices '(?y ?\s ?n ?
\177 ?
! ?q ?\e
)))
1208 t
) ; accept, and don't ask again
1209 ((memq char
'(?q ?\e
))
1210 nil
) ; skip, and don't ask again
1211 (t ; no previous answer - ask now
1213 (concat (apply #'format-message prompt args
)
1215 (format " [Type yn!q or %s] "
1216 (key-description (vector help-char
)))
1217 " [Type y, n, q or !] ")))
1218 (set sym
(setq char
(read-char-choice prompt char-choices
)))
1219 (if (memq char
'(?y ?\s ?
!)) t
)))))
1223 (defun dired-do-compress (&optional arg
)
1224 "Compress or uncompress marked (or next ARG) files."
1226 (dired-map-over-marks-check #'dired-compress arg
'compress t
))
1228 ;; Commands for Emacs Lisp files - load and byte compile
1230 (defun dired-byte-compile ()
1231 ;; Return nil for success, offending file name else.
1232 (let* ((filename (dired-get-filename))
1233 elc-file buffer-read-only failure
)
1235 (save-excursion (byte-compile-file filename
))
1237 (setq failure err
)))
1238 (setq elc-file
(byte-compile-dest-file filename
))
1239 (or (file-exists-p elc-file
)
1243 (dired-log "Byte compile error for %s:\n%s\n" filename failure
)
1244 (dired-make-relative filename
))
1245 (dired-remove-file elc-file
)
1246 (forward-line) ; insert .elc after its .el file
1247 (dired-add-file elc-file
)
1251 (defun dired-do-byte-compile (&optional arg
)
1252 "Byte compile marked (or next ARG) Emacs Lisp files."
1254 (dired-map-over-marks-check #'dired-byte-compile arg
'byte-compile t
))
1256 (defun dired-load ()
1257 ;; Return nil for success, offending file name else.
1258 (let ((file (dired-get-filename)) failure
)
1260 (load file nil nil t
)
1261 (error (setq failure err
)))
1264 (dired-log "Load error for %s:\n%s\n" file failure
)
1265 (dired-make-relative file
))))
1268 (defun dired-do-load (&optional arg
)
1269 "Load the marked (or next ARG) Emacs Lisp files."
1271 (dired-map-over-marks-check #'dired-load arg
'load t
))
1274 (defun dired-do-redisplay (&optional arg test-for-subdir
)
1275 "Redisplay all marked (or next ARG) files.
1276 If on a subdir line, redisplay that subdirectory. In that case,
1277 a prefix arg lets you edit the `ls' switches used for the new listing.
1279 Dired remembers switches specified with a prefix arg, so that reverting
1280 the buffer will not reset them. However, using `dired-undo' to re-insert
1281 or delete subdirectories can bypass this machinery. Hence, you sometimes
1282 may have to reset some subdirectory switches after a `dired-undo'.
1283 You can reset all subdirectory switches to the default using
1284 \\<dired-mode-map>\\[dired-reset-subdir-switches].
1285 See Info node `(emacs)Subdir switches' for more details."
1286 ;; Moves point if the next ARG files are redisplayed.
1287 (interactive "P\np")
1288 (if (and test-for-subdir
(dired-get-subdir))
1289 (let* ((dir (dired-get-subdir))
1290 (switches (cdr (assoc-string dir dired-switches-alist
))))
1291 (dired-insert-subdir
1294 (read-string "Switches for listing: "
1296 dired-subdir-switches
1297 dired-actual-switches
)))))
1298 (message "Redisplaying...")
1299 ;; message much faster than making dired-map-over-marks show progress
1301 (if (consp dired-directory
) (car dired-directory
) dired-directory
))
1302 (dired-map-over-marks (let ((fname (dired-get-filename nil t
))
1303 ;; Postpone readin hook till we map
1304 ;; over all marked files (Bug#6810).
1305 (dired-after-readin-hook nil
))
1307 (error "No file on this line")
1308 (message "Redisplaying... %s" fname
)
1309 (dired-update-file-line fname
)))
1311 (run-hooks 'dired-after-readin-hook
)
1312 (dired-move-to-filename)
1313 (message "Redisplaying...done")))
1315 (defun dired-reset-subdir-switches ()
1316 "Set `dired-switches-alist' to nil and revert dired buffer."
1318 (setq dired-switches-alist nil
)
1321 (defun dired-update-file-line (file)
1322 ;; Delete the current line, and insert an entry for FILE.
1323 ;; If FILE is nil, then just delete the current line.
1324 ;; Keeps any marks that may be present in column one (doing this
1325 ;; here is faster than with dired-add-entry's optional arg).
1326 ;; Does not update other dired buffers. Use dired-relist-entry for that.
1327 (let* ((opoint (line-beginning-position))
1328 (char (char-after opoint
))
1330 (delete-region opoint
(progn (forward-line 1) (point)))
1333 (dired-add-entry file nil t
)
1334 ;; Replace space by old marker without moving point.
1335 ;; Faster than goto+insdel inside a save-excursion?
1337 (subst-char-in-region opoint
(1+ opoint
) ?
\040 char
)))))
1338 (dired-move-to-filename))
1341 (defun dired-add-file (filename &optional marker-char
)
1342 (dired-fun-in-all-buffers
1343 (file-name-directory filename
) (file-name-nondirectory filename
)
1344 #'dired-add-entry filename marker-char
))
1346 (defvar dired-omit-mode
)
1347 (declare-function dired-omit-regexp
"dired-x" ())
1348 (defvar dired-omit-localp
)
1350 (defun dired-add-entry (filename &optional marker-char relative
)
1351 "Add a new dired entry for FILENAME.
1352 Optionally mark it with MARKER-CHAR (a character, else uses
1353 `dired-marker-char'). Note that this adds the entry `out of order'
1354 if files are sorted by time, etc.
1355 Skips files that match `dired-trivial-filenames'.
1356 Exposes hidden subdirectories if a file is added there.
1358 If `dired-x' is loaded and `dired-omit-mode' is enabled, skips
1359 files matching `dired-omit-regexp'."
1360 (if (or (not (featurep 'dired-x
))
1361 (not dired-omit-mode
)
1362 ;; Avoid calling ls for files that are going to be omitted anyway.
1363 (let ((omit-re (dired-omit-regexp)))
1364 (or (string= omit-re
"")
1365 (not (string-match-p omit-re
1367 ((eq 'no-dir dired-omit-localp
)
1369 ((eq t dired-omit-localp
)
1370 (dired-make-relative filename
))
1372 (dired-make-absolute
1374 (file-name-directory filename
)))))))))
1377 (setq filename
(directory-file-name filename
))
1378 ;; Entry is always for files, even if they happen to also be directories
1379 (let* ((opoint (point))
1380 (cur-dir (dired-current-directory))
1381 (directory (if relative cur-dir
(file-name-directory filename
)))
1385 (file-relative-name filename directory
)
1386 (file-name-nondirectory filename
))
1389 (if (string= directory cur-dir
)
1391 (skip-chars-forward "^\r\n")
1392 (if (eq (following-char) ?
\r)
1393 (dired-unhide-subdir))
1394 ;; We are already where we should be, except when
1395 ;; point is before the subdir line or its total line.
1396 (let ((p (dired-after-subdir-garbage cur-dir
)))
1399 ;; else try to find correct place to insert
1400 (if (dired-goto-subdir directory
)
1401 (progn ;; unhide if necessary
1402 (if (looking-at-p "\r")
1403 ;; Point is at end of subdir line.
1404 (dired-unhide-subdir))
1405 ;; found - skip subdir and `total' line
1406 ;; and uninteresting files like . and ..
1407 ;; This better not move into the next subdir!
1408 (dired-goto-next-nontrivial-file))
1410 (throw 'not-found
"Subdir not found")))
1411 (let (buffer-read-only opoint
)
1413 (setq opoint
(point))
1414 ;; Don't expand `.'.
1415 ;; Show just the file name within directory.
1416 (let ((default-directory directory
))
1417 (dired-insert-directory
1419 (concat dired-actual-switches
" -d")
1422 ;; Put in desired marker char.
1424 (let ((dired-marker-char
1425 (if (integerp marker-char
) marker-char
1426 dired-marker-char
)))
1428 ;; Compensate for a bug in ange-ftp.
1429 ;; It inserts the file's absolute name, rather than
1430 ;; the relative one. That may be hard to fix since it
1431 ;; is probably controlled by something in ftp.
1433 (let ((inserted-name (dired-get-filename 'verbatim
)))
1434 (if (file-name-directory inserted-name
)
1437 (forward-char (- (length inserted-name
)))
1438 (setq props
(text-properties-at (point)))
1439 (delete-char (length inserted-name
))
1442 (set-text-properties pt
(point) props
))
1446 (if dired-after-readin-hook
1447 ;; The subdir-alist is not affected...
1448 (save-excursion ; ...so we can run it right now:
1451 (narrow-to-region (point)
1452 (line-beginning-position 2))
1453 (run-hooks 'dired-after-readin-hook
))))
1454 (dired-move-to-filename))
1455 ;; return nil if all went well
1457 (if reason
; don't move away on failure
1459 (not reason
))) ; return t on success, nil else
1460 ;; Don't do it (dired-omit-mode).
1461 ;; Return t for success (perhaps we should return file-exists-p).
1464 (defun dired-after-subdir-garbage (dir)
1465 ;; Return pos of first file line of DIR, skipping header and total
1466 ;; or wildcard lines.
1467 ;; Important: never moves into the next subdir.
1468 ;; DIR is assumed to be unhidden.
1470 (or (dired-goto-subdir dir
) (error "This cannot happen"))
1472 (while (and (not (eolp)) ; don't cross subdir boundary
1473 (not (dired-move-to-filename)))
1478 (defun dired-remove-file (file)
1479 (dired-fun-in-all-buffers
1480 (file-name-directory file
) (file-name-nondirectory file
)
1481 #'dired-remove-entry file
))
1483 (defun dired-remove-entry (file)
1485 (and (dired-goto-file file
)
1486 (let (buffer-read-only)
1487 (delete-region (progn (beginning-of-line) (point))
1488 (line-beginning-position 2))))))
1491 (defun dired-relist-file (file)
1492 "Create or update the line for FILE in all Dired buffers it would belong in."
1493 (dired-fun-in-all-buffers (file-name-directory file
)
1494 (file-name-nondirectory file
)
1495 #'dired-relist-entry file
))
1497 (defun dired-relist-entry (file)
1498 ;; Relist the line for FILE, or just add it if it did not exist.
1499 ;; FILE must be an absolute file name.
1500 (let (buffer-read-only marker
)
1501 ;; If cursor is already on FILE's line delete-region will cause
1502 ;; save-excursion to fail because of floating makers,
1503 ;; moving point to beginning of line. Sigh.
1505 (and (dired-goto-file file
)
1506 (delete-region (progn (beginning-of-line)
1507 (setq marker
(following-char))
1509 (line-beginning-position 2)))
1510 (setq file
(directory-file-name file
))
1511 (dired-add-entry file
(if (eq ?
\040 marker
) nil marker
)))))
1513 ;;; Copy, move/rename, making hard and symbolic links
1515 (defcustom dired-backup-overwrite nil
1516 "Non-nil if Dired should ask about making backups before overwriting files.
1517 Special value `always' suppresses confirmation."
1518 :type
'(choice (const :tag
"off" nil
)
1519 (const :tag
"suppress" always
)
1520 (other :tag
"ask" t
))
1523 ;; This is a fluid var used in dired-handle-overwrite. It should be
1524 ;; let-bound whenever dired-copy-file etc are called. See
1525 ;; dired-create-files for an example.
1526 (defvar dired-overwrite-confirmed
)
1528 (defun dired-handle-overwrite (to)
1529 ;; Save old version of file TO that is to be overwritten.
1530 ;; `dired-overwrite-confirmed' and `overwrite-backup-query' are fluid vars
1531 ;; from dired-create-files.
1533 (when (and dired-backup-overwrite
1534 dired-overwrite-confirmed
1535 (setq backup
(car (find-backup-file-name to
)))
1536 (or (eq 'always dired-backup-overwrite
)
1537 (dired-query 'overwrite-backup-query
1538 "Make backup for existing file `%s'? "
1540 (rename-file to backup
0) ; confirm overwrite of old backup
1541 (dired-relist-entry backup
))))
1544 (defun dired-copy-file (from to ok-flag
)
1545 (dired-handle-overwrite to
)
1546 (dired-copy-file-recursive from to ok-flag dired-copy-preserve-time t
1547 dired-recursive-copies
))
1549 (declare-function make-symbolic-link
"fileio.c")
1551 (defun dired-copy-file-recursive (from to ok-flag
&optional
1552 preserve-time top recursive
)
1553 (when (and (eq t
(car (file-attributes from
)))
1554 (file-in-directory-p to from
))
1555 (error "Cannot copy `%s' into its subdirectory `%s'" from to
))
1556 (let ((attrs (file-attributes from
)))
1559 (or (eq recursive
'always
)
1560 (yes-or-no-p (format "Recursive copies of %s? " from
))))
1561 (copy-directory from to preserve-time
)
1562 (or top
(dired-handle-overwrite to
))
1564 (if (stringp (car attrs
))
1566 (make-symbolic-link (car attrs
) to ok-flag
)
1567 (copy-file from to ok-flag preserve-time
))
1569 (push (dired-make-relative from
)
1570 dired-create-files-failures
)
1571 (dired-log "Can't set date on %s:\n%s\n" from err
))))))
1574 (defun dired-rename-file (file newname ok-if-already-exists
)
1575 (dired-handle-overwrite newname
)
1576 (rename-file file newname ok-if-already-exists
) ; error is caught in -create-files
1577 ;; Silently rename the visited file of any buffer visiting this file.
1578 (and (get-file-buffer file
)
1579 (with-current-buffer (get-file-buffer file
)
1580 (set-visited-file-name newname nil t
)))
1581 (dired-remove-file file
)
1582 ;; See if it's an inserted subdir, and rename that, too.
1583 (dired-rename-subdir file newname
))
1585 (defun dired-rename-subdir (from-dir to-dir
)
1586 (setq from-dir
(file-name-as-directory from-dir
)
1587 to-dir
(file-name-as-directory to-dir
))
1588 (dired-fun-in-all-buffers from-dir nil
1589 #'dired-rename-subdir-1 from-dir to-dir
)
1590 ;; Update visited file name of all affected buffers
1591 (let ((expanded-from-dir (expand-file-name from-dir
))
1592 (blist (buffer-list)))
1594 (with-current-buffer (car blist
)
1595 (if (and buffer-file-name
1596 (dired-in-this-tree buffer-file-name expanded-from-dir
))
1597 (let ((modflag (buffer-modified-p))
1598 (to-file (dired-replace-in-string
1599 (concat "^" (regexp-quote from-dir
))
1602 (set-visited-file-name to-file
)
1603 (set-buffer-modified-p modflag
))))
1604 (setq blist
(cdr blist
)))))
1606 (defun dired-rename-subdir-1 (dir to
)
1607 ;; Rename DIR to TO in headerlines and dired-subdir-alist, if DIR or
1608 ;; one of its subdirectories is expanded in this buffer.
1609 (let ((expanded-dir (expand-file-name dir
))
1610 (alist dired-subdir-alist
)
1613 (setq elt
(car alist
)
1615 (if (dired-in-this-tree (car elt
) expanded-dir
)
1616 ;; ELT's subdir is affected by the rename
1617 (dired-rename-subdir-2 elt dir to
)))
1618 (if (equal dir default-directory
)
1619 ;; if top level directory was renamed, lots of things have to be
1622 (dired-unadvertise dir
) ; we no longer dired DIR...
1623 (setq default-directory to
1624 dired-directory
(expand-file-name;; this is correct
1625 ;; with and without wildcards
1626 (file-name-nondirectory dired-directory
)
1628 (let ((new-name (file-name-nondirectory
1629 (directory-file-name dired-directory
))))
1630 ;; try to rename buffer, but just leave old name if new
1631 ;; name would already exist (don't try appending "<%d>")
1632 (or (get-buffer new-name
)
1633 (rename-buffer new-name
)))
1634 ;; ... we dired TO now:
1635 (dired-advertise)))))
1637 (defun dired-rename-subdir-2 (elt dir to
)
1638 ;; Update the headerline and dired-subdir-alist element, as well as
1639 ;; dired-switches-alist element, of directory described by
1640 ;; alist-element ELT to reflect the moving of DIR to TO. Thus, ELT
1641 ;; describes either DIR itself or a subdir of DIR.
1643 (let ((regexp (regexp-quote (directory-file-name dir
)))
1644 (newtext (directory-file-name to
))
1646 (goto-char (dired-get-subdir-min elt
))
1647 ;; Update subdir headerline in buffer
1648 (if (not (looking-at dired-subdir-regexp
))
1649 (error "%s not found where expected - dired-subdir-alist broken?"
1651 (goto-char (match-beginning 1))
1652 (if (re-search-forward regexp
(match-end 1) t
)
1653 (replace-match newtext t t
)
1654 (error "Expected to find `%s' in headerline of %s" dir
(car elt
))))
1655 ;; Update buffer-local dired-subdir-alist and dired-switches-alist
1656 (let ((cons (assoc-string (car elt
) dired-switches-alist
))
1657 (cur-dir (dired-normalize-subdir
1658 (dired-replace-in-string regexp newtext
(car elt
)))))
1659 (setcar elt cur-dir
)
1660 (when cons
(setcar cons cur-dir
))))))
1662 ;; Bound in dired-create-files
1663 (defvar overwrite-query
)
1664 (defvar overwrite-backup-query
)
1666 ;; The basic function for half a dozen variations on cp/mv/ln/ln -s.
1667 (defun dired-create-files (file-creator operation fn-list name-constructor
1668 &optional marker-char
)
1669 "Create one or more new files from a list of existing files FN-LIST.
1670 This function also handles querying the user, updating Dired
1671 buffers, and displaying a success or failure message.
1673 FILE-CREATOR should be a function. It is called once for each
1674 file in FN-LIST, and must create a new file, querying the user
1675 and updating Dired buffers as necessary. It should accept three
1676 arguments: the old file name, the new name, and an argument
1677 OK-IF-ALREADY-EXISTS with the same meaning as in `copy-file'.
1679 OPERATION should be a capitalized string describing the operation
1680 performed (e.g. `Copy'). It is used for error logging.
1682 FN-LIST is the list of files to copy (full absolute file names).
1684 NAME-CONSTRUCTOR should be a function accepting a single
1685 argument, the name of an old file, and returning either the
1686 corresponding new file name or nil to skip.
1688 If optional argument MARKER-CHAR is non-nil, mark each
1689 newly-created file's Dired entry with the character MARKER-CHAR,
1690 or with the current marker character if MARKER-CHAR is t."
1691 (let (dired-create-files-failures failures
1692 skipped
(success-count 0) (total (length fn-list
)))
1693 (let (to overwrite-query
1694 overwrite-backup-query
) ; for dired-handle-overwrite
1695 (dolist (from fn-list
)
1696 (setq to
(funcall name-constructor from
))
1700 (dired-log "Cannot %s to same file: %s\n"
1701 (downcase operation
) from
)))
1703 (setq skipped
(cons (dired-make-relative from
) skipped
))
1704 (let* ((overwrite (file-exists-p to
))
1705 (dired-overwrite-confirmed ; for dired-handle-overwrite
1707 (let ((help-form '(format-message "\
1708 Type SPC or `y' to overwrite file `%s',
1709 DEL or `n' to skip to next,
1710 ESC or `q' to not overwrite any of the remaining files,
1711 `!' to overwrite all remaining files with no more questions." to
)))
1712 (dired-query 'overwrite-query
1713 "Overwrite `%s'?" to
))))
1714 ;; must determine if FROM is marked before file-creator
1715 ;; gets a chance to delete it (in case of a move).
1717 (cond ((integerp marker-char
) marker-char
)
1718 (marker-char (dired-file-marker from
)) ; slow
1720 ;; Handle the `dired-copy-file' file-creator specially
1721 ;; When copying a directory to another directory or
1722 ;; possibly to itself or one of its subdirectories.
1723 ;; e.g "~/foo/" => "~/test/"
1724 ;; or "~/foo/" =>"~/foo/"
1725 ;; or "~/foo/ => ~/foo/bar/")
1726 ;; In this case the 'name-constructor' have set the destination
1727 ;; TO to "~/test/foo" because the old emacs23 behavior
1728 ;; of `copy-directory' was to not create the subdirectory
1729 ;; and instead copy the contents.
1730 ;; With the new behavior of `copy-directory'
1731 ;; (similar to the `cp' shell command) we don't
1732 ;; need such a construction of the target directory,
1733 ;; so modify the destination TO to "~/test/" instead of "~/test/foo/".
1734 (let ((destname (file-name-directory to
)))
1735 (when (and (file-directory-p from
)
1736 (file-directory-p to
)
1737 (eq file-creator
'dired-copy-file
))
1739 ;; If DESTNAME is a subdirectory of FROM, not a symlink,
1740 ;; and the method in use is copying, signal an error.
1741 (and (eq t
(car (file-attributes destname
)))
1742 (eq file-creator
'dired-copy-file
)
1743 (file-in-directory-p destname from
)
1744 (error "Cannot copy `%s' into its subdirectory `%s'"
1748 (funcall file-creator from to dired-overwrite-confirmed
)
1750 ;; If we get here, file-creator hasn't been aborted
1751 ;; and the old entry (if any) has to be deleted
1752 ;; before adding the new entry.
1753 (dired-remove-file to
))
1754 (setq success-count
(1+ success-count
))
1755 (message "%s: %d of %d" operation success-count total
)
1756 (dired-add-file to actual-marker-char
))
1757 (file-error ; FILE-CREATOR aborted
1759 (push (dired-make-relative from
)
1761 (dired-log "%s `%s' to `%s' failed:\n%s\n"
1762 operation from to err
))))))))
1764 (dired-create-files-failures
1765 (setq failures
(nconc failures dired-create-files-failures
))
1767 (format "%s failed for %d file%s in %d requests"
1768 operation
(length failures
)
1769 (dired-plural-s (length failures
))
1774 (format "%s failed for %d of %d file%s"
1775 operation
(length failures
)
1776 total
(dired-plural-s total
))
1780 (format "%s: %d of %d file%s skipped"
1781 operation
(length skipped
) total
1782 (dired-plural-s total
))
1785 (message "%s: %s file%s"
1786 operation success-count
(dired-plural-s success-count
)))))
1787 (dired-move-to-filename))
1789 (defun dired-do-create-files (op-symbol file-creator operation arg
1790 &optional marker-char op1
1792 "Create a new file for each marked file.
1793 Prompt user for a target directory in which to create the new
1794 files. The target may also be a non-directory file, if only
1795 one file is marked. The initial suggestion for target is the
1796 Dired buffer's current directory (or, if `dired-dwim-target' is
1797 non-nil, the current directory of a neighboring Dired window).
1798 OP-SYMBOL is the symbol for the operation. Function `dired-mark-pop-up'
1799 will determine whether pop-ups are appropriate for this OP-SYMBOL.
1800 FILE-CREATOR and OPERATION as in `dired-create-files'.
1801 ARG as in `dired-get-marked-files'.
1802 Optional arg MARKER-CHAR as in `dired-create-files'.
1803 Optional arg OP1 is an alternate form for OPERATION if there is
1805 Optional arg HOW-TO determines how to treat the target.
1806 If HOW-TO is nil, use `file-directory-p' to determine if the
1807 target is a directory. If so, the marked file(s) are created
1808 inside that directory. Otherwise, the target is a plain file;
1809 an error is raised unless there is exactly one marked file.
1810 If HOW-TO is t, target is always treated as a plain file.
1811 Otherwise, HOW-TO should be a function of one argument, TARGET.
1812 If its return value is nil, TARGET is regarded as a plain file.
1813 If it return value is a list, TARGET is a generalized
1814 directory (e.g. some sort of archive). The first element of
1815 this list must be a function with at least four arguments:
1816 operation - as OPERATION above.
1817 rfn-list - list of the relative names for the marked files.
1818 fn-list - list of the absolute names for the marked files.
1819 target - the name of the target itself.
1820 The rest of into-dir are optional arguments.
1821 For any other return value, TARGET is treated as a directory."
1822 (or op1
(setq op1 operation
))
1823 (let* ((fn-list (dired-get-marked-files nil arg
))
1824 (rfn-list (mapcar #'dired-make-relative fn-list
))
1825 (dired-one-file ; fluid variable inside dired-create-files
1826 (and (consp fn-list
) (null (cdr fn-list
)) (car fn-list
)))
1827 (target-dir (dired-dwim-target-directory))
1828 (default (and dired-one-file
1829 (not dired-dwim-target
) ; Bug#25609
1830 (expand-file-name (file-name-nondirectory (car fn-list
))
1832 (defaults (dired-dwim-target-defaults fn-list target-dir
))
1833 (target (expand-file-name ; fluid variable inside dired-create-files
1834 (minibuffer-with-setup-hook
1836 (set (make-local-variable 'minibuffer-default-add-function
) nil
)
1837 (setq minibuffer-default defaults
))
1838 (dired-mark-read-file-name
1839 (concat (if dired-one-file op1 operation
) " %s to: ")
1840 target-dir op-symbol arg rfn-list default
))))
1841 (into-dir (cond ((null how-to
)
1842 ;; Allow users to change the letter case of
1843 ;; a directory on a case-insensitive
1844 ;; filesystem. If we don't test these
1845 ;; conditions up front, file-directory-p
1846 ;; below will return t on a case-insensitive
1847 ;; filesystem, and Emacs will try to move
1848 ;; foo -> foo/foo, which fails.
1849 (if (and (file-name-case-insensitive-p (car fn-list
))
1850 (eq op-symbol
'move
)
1853 (expand-file-name (car fn-list
)))
1855 (expand-file-name target
)))
1857 (file-name-nondirectory (car fn-list
))
1858 (file-name-nondirectory target
))))
1860 (file-directory-p target
)))
1862 (t (funcall how-to target
)))))
1863 (if (and (consp into-dir
) (functionp (car into-dir
)))
1864 (apply (car into-dir
) operation rfn-list fn-list target
(cdr into-dir
))
1865 (if (not (or dired-one-file into-dir
))
1866 (error "Marked %s: target must be a directory: %s" operation target
))
1867 ;; rename-file bombs when moving directories unless we do this:
1868 (or into-dir
(setq target
(directory-file-name target
)))
1870 file-creator operation fn-list
1871 (if into-dir
; target is a directory
1872 ;; This function uses fluid variable target when called
1873 ;; inside dired-create-files:
1875 (expand-file-name (file-name-nondirectory from
) target
))
1876 (lambda (_from) target
))
1879 ;; Read arguments for a marked-files command that wants a file name,
1880 ;; perhaps popping up the list of marked files.
1881 ;; ARG is the prefix arg and indicates whether the files came from
1882 ;; marks (ARG=nil) or a repeat factor (integerp ARG).
1883 ;; If the current file was used, the list has but one element and ARG
1884 ;; does not matter. (It is non-nil, non-integer in that case, namely '(4)).
1885 ;; DEFAULT is the default value to return if the user just hits RET;
1886 ;; if it is omitted or nil, then the name of the directory is used.
1888 (defun dired-mark-read-file-name (prompt dir op-symbol arg files
1893 (format prompt
(dired-mark-prompt arg files
)) dir default
))
1895 (defun dired-dwim-target-directory ()
1896 ;; Try to guess which target directory the user may want.
1897 ;; If there is a dired buffer displayed in one of the next windows,
1898 ;; use its current subdir, else use current subdir of this dired buffer.
1899 (let ((this-dir (and (eq major-mode
'dired-mode
)
1900 (dired-current-directory))))
1901 ;; non-dired buffer may want to profit from this function, e.g. vm-uudecode
1902 (if dired-dwim-target
1903 (let* ((other-win (get-window-with-predicate
1905 (with-current-buffer (window-buffer window
)
1906 (eq major-mode
'dired-mode
)))))
1907 (other-dir (and other-win
1908 (with-current-buffer (window-buffer other-win
)
1909 (and (eq major-mode
'dired-mode
)
1910 (dired-current-directory))))))
1911 (or other-dir this-dir
))
1914 (defun dired-dwim-target-defaults (fn-list target-dir
)
1915 ;; Return a list of default values for file-reading functions in Dired.
1916 ;; This list may contain directories from Dired buffers in other windows.
1917 ;; `fn-list' is a list of file names used to build a list of defaults.
1918 ;; When nil or more than one element, a list of defaults will
1919 ;; contain only directory names. `target-dir' is a directory name
1920 ;; to exclude from the returned list, for the case when this
1921 ;; directory name is already presented in initial input.
1922 ;; For Dired operations that support `dired-dwim-target',
1923 ;; the argument `target-dir' should have the value returned
1924 ;; from `dired-dwim-target-directory'.
1925 (let ((dired-one-file
1926 (and (consp fn-list
) (null (cdr fn-list
)) (car fn-list
)))
1927 (current-dir (and (eq major-mode
'dired-mode
)
1928 (dired-current-directory)))
1930 ;; Get a list of directories of visible buffers in dired-mode.
1931 (walk-windows (lambda (w)
1932 (with-current-buffer (window-buffer w
)
1933 (and (eq major-mode
'dired-mode
)
1934 (push (dired-current-directory) dired-dirs
)))))
1935 ;; Force the current dir to be the first in the list.
1937 (delete-dups (delq nil
(cons current-dir
(nreverse dired-dirs
)))))
1938 ;; Remove the target dir (if specified) or the current dir from
1939 ;; default values, because it should be already in initial input.
1940 (setq dired-dirs
(delete (or target-dir current-dir
) dired-dirs
))
1941 ;; Return a list of default values.
1943 ;; For one file operation, provide a list that contains
1944 ;; other directories, other directories with the appended filename
1945 ;; and the current directory with the appended filename, e.g.
1947 ;; 2. /TARGET-DIR/FILENAME
1948 ;; 3. /CURRENT-DIR/FILENAME
1950 (mapcar (lambda (dir)
1952 (file-name-nondirectory (car fn-list
)) dir
))
1953 (reverse dired-dirs
))
1954 (list (expand-file-name
1955 (file-name-nondirectory (car fn-list
))
1956 (or target-dir current-dir
))))
1957 ;; For multi-file operation, return only a list of other directories.
1962 (defun dired-create-directory (directory)
1963 "Create a directory called DIRECTORY.
1964 If DIRECTORY already exists, signal an error."
1966 (list (read-file-name "Create directory: " (dired-current-directory))))
1967 (let* ((expanded (directory-file-name (expand-file-name directory
)))
1969 (if (file-exists-p expanded
)
1970 (error "Cannot create directory %s: file exists" expanded
))
1971 ;; Find the topmost nonexistent parent dir (variable `new')
1972 (while (and try
(not (file-exists-p try
)) (not (equal new try
)))
1974 try
(directory-file-name (file-name-directory try
))))
1975 (make-directory expanded t
)
1977 (dired-add-file new
)
1978 (dired-move-to-filename))))
1980 (defun dired-into-dir-with-symlinks (target)
1981 (and (file-directory-p target
)
1982 (not (file-symlink-p target
))))
1983 ;; This may not always be what you want, especially if target is your
1984 ;; home directory and it happens to be a symbolic link, as is often the
1985 ;; case with NFS and automounters. Or if you want to make symlinks
1986 ;; into directories that themselves are only symlinks, also quite
1989 ;; So we don't use this function as value for HOW-TO in
1990 ;; dired-do-symlink, which has the minor disadvantage of
1991 ;; making links *into* a symlinked-dir, when you really wanted to
1992 ;; *overwrite* that symlink. In that (rare, I guess) case, you'll
1993 ;; just have to remove that symlink by hand before making your marked
1996 (defvar dired-copy-how-to-fn nil
1997 "Either nil or a function used by `dired-do-copy' to determine target.
1998 See HOW-TO argument for `dired-do-create-files'.")
2001 (defun dired-do-copy (&optional arg
)
2002 "Copy all marked (or next ARG) files, or copy the current file.
2003 When operating on just the current file, prompt for the new name.
2005 When operating on multiple or marked files, prompt for a target
2006 directory, and make the new copies in that directory, with the
2007 same names as the original files. The initial suggestion for the
2008 target directory is the Dired buffer's current directory (or, if
2009 `dired-dwim-target' is non-nil, the current directory of a
2010 neighboring Dired window).
2012 If `dired-copy-preserve-time' is non-nil, this command preserves
2013 the modification time of each old file in the copy, similar to
2014 the \"-p\" option for the \"cp\" shell command.
2016 This command copies symbolic links by creating new ones, similar
2017 to the \"-d\" option for the \"cp\" shell command."
2019 (let ((dired-recursive-copies dired-recursive-copies
))
2020 (dired-do-create-files 'copy
#'dired-copy-file
2022 arg dired-keep-marker-copy
2023 nil dired-copy-how-to-fn
)))
2026 (defun dired-do-symlink (&optional arg
)
2027 "Make symbolic links to current file or all marked (or next ARG) files.
2028 When operating on just the current file, you specify the new name.
2029 When operating on multiple or marked files, you specify a directory
2030 and new symbolic links are made in that directory
2031 with the same names that the files currently have. The default
2032 suggested for the target directory depends on the value of
2033 `dired-dwim-target', which see.
2035 For relative symlinks, use \\[dired-do-relsymlink]."
2037 (dired-do-create-files 'symlink
#'make-symbolic-link
2038 "Symlink" arg dired-keep-marker-symlink
))
2041 (defun dired-do-hardlink (&optional arg
)
2042 "Add names (hard links) current file or all marked (or next ARG) files.
2043 When operating on just the current file, you specify the new name.
2044 When operating on multiple or marked files, you specify a directory
2045 and new hard links are made in that directory
2046 with the same names that the files currently have. The default
2047 suggested for the target directory depends on the value of
2048 `dired-dwim-target', which see."
2050 (dired-do-create-files 'hardlink
#'dired-hardlink
2051 "Hardlink" arg dired-keep-marker-hardlink
))
2053 (defun dired-hardlink (file newname
&optional ok-if-already-exists
)
2054 (dired-handle-overwrite newname
)
2055 ;; error is caught in -create-files
2056 (add-name-to-file file newname ok-if-already-exists
)
2057 ;; Update the link count
2058 (dired-relist-file file
))
2061 (defun dired-do-rename (&optional arg
)
2062 "Rename current file or all marked (or next ARG) files.
2063 When renaming just the current file, you specify the new name.
2064 When renaming multiple or marked files, you specify a directory.
2065 This command also renames any buffers that are visiting the files.
2066 The default suggested for the target directory depends on the value
2067 of `dired-dwim-target', which see."
2069 (dired-do-create-files 'move
#'dired-rename-file
2070 "Move" arg dired-keep-marker-rename
"Rename"))
2071 ;;;###end dired-cp.el
2074 ;;;###begin dired-re.el
2075 (defvar rename-regexp-query
)
2077 (defun dired-do-create-files-regexp
2078 (file-creator operation arg regexp newname
&optional whole-name marker-char
)
2079 ;; Create a new file for each marked file using regexps.
2080 ;; FILE-CREATOR and OPERATION as in dired-create-files.
2081 ;; ARG as in dired-get-marked-files.
2082 ;; Matches each marked file against REGEXP and constructs the new
2083 ;; filename from NEWNAME (like in function replace-match).
2084 ;; Optional arg WHOLE-NAME means match/replace the whole file name
2085 ;; instead of only the non-directory part of the file.
2086 ;; Optional arg MARKER-CHAR as in dired-create-files.
2087 (let* ((fn-list (dired-get-marked-files nil arg
))
2088 (operation-prompt (concat operation
" `%s' to `%s'?"))
2089 (rename-regexp-help-form (format-message "\
2090 Type SPC or `y' to %s one match, DEL or `n' to skip to next,
2091 `!' to %s all remaining matches with no more questions."
2092 (downcase operation
)
2093 (downcase operation
)))
2094 (regexp-name-constructor
2095 ;; Function to construct new filename using REGEXP and NEWNAME:
2096 (if whole-name
; easy (but rare) case
2098 (let ((to (dired-string-replace-match regexp from newname
))
2099 ;; must bind help-form directly around call to
2101 (help-form rename-regexp-help-form
))
2103 (and (dired-query 'rename-regexp-query
2108 (dired-log "%s: %s did not match regexp %s\n"
2109 operation from regexp
))))
2110 ;; not whole-name, replace non-directory part only
2112 (let* ((new (dired-string-replace-match
2113 regexp
(file-name-nondirectory from
) newname
))
2114 (to (and new
; nil means there was no match
2115 (expand-file-name new
2116 (file-name-directory from
))))
2117 (help-form rename-regexp-help-form
))
2119 (and (dired-query 'rename-regexp-query
2121 (dired-make-relative from
)
2122 (dired-make-relative to
))
2124 (dired-log "%s: %s did not match regexp %s\n"
2125 operation
(file-name-nondirectory from
) regexp
))))))
2126 rename-regexp-query
)
2128 file-creator operation fn-list regexp-name-constructor marker-char
)))
2130 (defun dired-mark-read-regexp (operation)
2131 ;; Prompt user about performing OPERATION.
2132 ;; Read and return list of: regexp newname arg whole-name.
2134 (equal 0 (prefix-numeric-value current-prefix-arg
)))
2136 (if whole-name nil current-prefix-arg
))
2139 (concat (if whole-name
"Abs. " "") operation
" from (regexp): ")
2140 nil
'dired-regexp-history
))
2143 (concat (if whole-name
"Abs. " "") operation
" " regexp
" to: "))))
2144 (list regexp newname arg whole-name
)))
2147 (defun dired-do-rename-regexp (regexp newname
&optional arg whole-name
)
2148 "Rename selected files whose names match REGEXP to NEWNAME.
2150 With non-zero prefix argument ARG, the command operates on the next ARG
2151 files. Otherwise, it operates on all the marked files, or the current
2152 file if none are marked.
2154 As each match is found, the user must type a character saying
2155 what to do with it. For directions, type \\[help-command] at that time.
2156 NEWNAME may contain \\=\\<n> or \\& as in `query-replace-regexp'.
2157 REGEXP defaults to the last regexp used.
2159 With a zero prefix arg, renaming by regexp affects the absolute file name.
2160 Normally, only the non-directory part of the file name is used and changed."
2161 (interactive (dired-mark-read-regexp "Rename"))
2162 (dired-do-create-files-regexp
2164 "Rename" arg regexp newname whole-name dired-keep-marker-rename
))
2167 (defun dired-do-copy-regexp (regexp newname
&optional arg whole-name
)
2168 "Copy selected files whose names match REGEXP to NEWNAME.
2169 See function `dired-do-rename-regexp' for more info."
2170 (interactive (dired-mark-read-regexp "Copy"))
2171 (let ((dired-recursive-copies nil
)) ; No recursive copies.
2172 (dired-do-create-files-regexp
2174 (if dired-copy-preserve-time
"Copy [-p]" "Copy")
2175 arg regexp newname whole-name dired-keep-marker-copy
)))
2178 (defun dired-do-hardlink-regexp (regexp newname
&optional arg whole-name
)
2179 "Hardlink selected files whose names match REGEXP to NEWNAME.
2180 See function `dired-do-rename-regexp' for more info."
2181 (interactive (dired-mark-read-regexp "HardLink"))
2182 (dired-do-create-files-regexp
2184 "HardLink" arg regexp newname whole-name dired-keep-marker-hardlink
))
2187 (defun dired-do-symlink-regexp (regexp newname
&optional arg whole-name
)
2188 "Symlink selected files whose names match REGEXP to NEWNAME.
2189 See function `dired-do-rename-regexp' for more info."
2190 (interactive (dired-mark-read-regexp "SymLink"))
2191 (dired-do-create-files-regexp
2192 #'make-symbolic-link
2193 "SymLink" arg regexp newname whole-name dired-keep-marker-symlink
))
2195 (defvar rename-non-directory-query
)
2197 (defun dired-create-files-non-directory
2198 (file-creator basename-constructor operation arg
)
2199 ;; Perform FILE-CREATOR on the non-directory part of marked files
2200 ;; using function BASENAME-CONSTRUCTOR, with query for each file.
2201 ;; OPERATION like in dired-create-files, ARG as in dired-get-marked-files.
2202 (let (rename-non-directory-query)
2206 (dired-get-marked-files nil arg
)
2208 (let ((to (concat (file-name-directory from
)
2209 (funcall basename-constructor
2210 (file-name-nondirectory from
)))))
2211 (and (let ((help-form (format-message "\
2212 Type SPC or `y' to %s one file, DEL or `n' to skip to next,
2213 `!' to %s all remaining matches with no more questions."
2214 (downcase operation
)
2215 (downcase operation
))))
2216 (dired-query 'rename-non-directory-query
2217 (concat operation
" `%s' to `%s'")
2218 (dired-make-relative from
)
2219 (dired-make-relative to
)))
2221 dired-keep-marker-rename
)))
2223 (defun dired-rename-non-directory (basename-constructor operation arg
)
2224 (dired-create-files-non-directory
2226 basename-constructor operation arg
))
2229 (defun dired-upcase (&optional arg
)
2230 "Rename all marked (or next ARG) files to upper case."
2232 (dired-rename-non-directory #'upcase
"Rename upcase" arg
))
2235 (defun dired-downcase (&optional arg
)
2236 "Rename all marked (or next ARG) files to lower case."
2238 (dired-rename-non-directory #'downcase
"Rename downcase" arg
))
2240 ;;;###end dired-re.el
2243 ;;;###begin dired-ins.el
2246 (defun dired-maybe-insert-subdir (dirname &optional
2247 switches no-error-if-not-dir-p
)
2248 "Insert this subdirectory into the same dired buffer.
2249 If it is already present, just move to it (type \\[dired-do-redisplay] to refresh),
2250 else inserts it at its natural place (as `ls -lR' would have done).
2251 With a prefix arg, you may edit the ls switches used for this listing.
2252 You can add `R' to the switches to expand the whole tree starting at
2254 This function takes some pains to conform to `ls -lR' output.
2256 Dired remembers switches specified with a prefix arg, so that reverting
2257 the buffer will not reset them. However, using `dired-undo' to re-insert
2258 or delete subdirectories can bypass this machinery. Hence, you sometimes
2259 may have to reset some subdirectory switches after a `dired-undo'.
2260 You can reset all subdirectory switches to the default using
2261 \\<dired-mode-map>\\[dired-reset-subdir-switches].
2262 See Info node `(emacs)Subdir switches' for more details."
2264 (list (dired-get-filename)
2265 (if current-prefix-arg
2266 (read-string "Switches for listing: "
2267 (or dired-subdir-switches dired-actual-switches
)))))
2268 (let ((opoint (point)))
2269 ;; We don't need a marker for opoint as the subdir is always
2270 ;; inserted *after* opoint.
2271 (setq dirname
(file-name-as-directory dirname
))
2272 (or (and (not switches
)
2273 (when (dired-goto-subdir dirname
)
2274 (unless (dired-subdir-hidden-p dirname
)
2275 (dired-initial-position dirname
))
2277 (dired-insert-subdir dirname switches no-error-if-not-dir-p
))
2278 ;; Push mark so that it's easy to find back. Do this after the
2279 ;; insert message so that the user sees the `Mark set' message.
2280 (push-mark opoint
)))
2283 (defun dired-insert-subdir (dirname &optional switches no-error-if-not-dir-p
)
2284 "Insert this subdirectory into the same Dired buffer.
2285 If it is already present, overwrite the previous entry;
2286 otherwise, insert it at its natural place (as `ls -lR' would
2288 With a prefix arg, you may edit the `ls' switches used for this listing.
2289 You can add `R' to the switches to expand the whole tree starting at
2291 This function takes some pains to conform to `ls -lR' output."
2292 ;; NO-ERROR-IF-NOT-DIR-P needed for special filesystems like
2293 ;; Prospero where dired-ls does the right thing, but
2294 ;; file-directory-p has not been redefined.
2296 (list (dired-get-filename)
2297 (if current-prefix-arg
2298 (read-string "Switches for listing: "
2299 (or dired-subdir-switches dired-actual-switches
)))))
2300 (setq dirname
(file-name-as-directory (expand-file-name dirname
)))
2301 (or no-error-if-not-dir-p
2302 (file-directory-p dirname
)
2303 (error "Attempt to insert a non-directory: %s" dirname
))
2304 (let ((elt (assoc dirname dired-subdir-alist
))
2305 (cons (assoc-string dirname dired-switches-alist
))
2306 (modflag (buffer-modified-p))
2307 (old-switches switches
)
2308 switches-have-R mark-alist case-fold-search buffer-read-only
)
2309 (and (not switches
) cons
(setq switches
(cdr cons
)))
2310 (dired-insert-subdir-validate dirname switches
)
2311 ;; case-fold-search is nil now, so we can test for capital `R':
2312 (if (setq switches-have-R
(and switches
(string-match-p "R" switches
)))
2313 ;; avoid duplicated subdirs
2314 (setq mark-alist
(dired-kill-tree dirname t
)))
2316 ;; If subdir is already present, remove it and remember its marks
2317 (setq mark-alist
(nconc (dired-insert-subdir-del elt
) mark-alist
))
2318 (dired-insert-subdir-newpos dirname
)) ; else compute new position
2319 (dired-insert-subdir-doupdate
2320 dirname elt
(dired-insert-subdir-doinsert dirname switches
))
2323 (setcdr cons switches
)
2324 (push (cons dirname switches
) dired-switches-alist
)))
2325 (when switches-have-R
2326 (dired-build-subdir-alist switches
)
2327 (setq switches
(dired-replace-in-string "R" "" switches
))
2328 (dolist (cur-ass dired-subdir-alist
)
2329 (let ((cur-dir (car cur-ass
)))
2330 (and (dired-in-this-tree cur-dir dirname
)
2331 (let ((cur-cons (assoc-string cur-dir dired-switches-alist
)))
2333 (setcdr cur-cons switches
)
2334 (push (cons cur-dir switches
) dired-switches-alist
)))))))
2335 (dired-initial-position dirname
)
2336 (save-excursion (dired-mark-remembered mark-alist
))
2337 (restore-buffer-modified-p modflag
)))
2339 (defun dired-insert-subdir-validate (dirname &optional switches
)
2340 ;; Check that it is valid to insert DIRNAME with SWITCHES.
2341 ;; Signal an error if invalid (e.g. user typed `i' on `..').
2342 (or (dired-in-this-tree dirname
(expand-file-name default-directory
))
2343 (error "%s: not in this directory tree" dirname
))
2344 (let ((real-switches (or switches dired-subdir-switches
)))
2346 (let (case-fold-search)
2349 (or (eq (null (string-match-p x real-switches
))
2350 (null (string-match-p x dired-actual-switches
)))
2352 "Can't have dirs with and without -%s switches together" x
)))
2353 ;; all switches that make a difference to dired-get-filename:
2356 (defun dired-alist-add (dir new-marker
)
2357 ;; Add new DIR at NEW-MARKER. Sort alist.
2358 (dired-alist-add-1 dir new-marker
)
2361 (defun dired-alist-sort ()
2362 ;; Keep the alist sorted on buffer position.
2363 (setq dired-subdir-alist
2364 (sort dired-subdir-alist
2366 (> (dired-get-subdir-min elt1
)
2367 (dired-get-subdir-min elt2
))))))
2369 (defun dired-kill-tree (dirname &optional remember-marks kill-root
)
2370 "Kill all proper subdirs of DIRNAME, excluding DIRNAME itself.
2371 Interactively, you can kill DIRNAME as well by using a prefix argument.
2372 In interactive use, the command prompts for DIRNAME.
2374 When called from Lisp, if REMEMBER-MARKS is non-nil, return an alist
2375 of marked files. If KILL-ROOT is non-nil, kill DIRNAME as well."
2376 (interactive "DKill tree below directory: \ni\nP")
2377 (setq dirname
(file-name-as-directory (expand-file-name dirname
)))
2378 (let ((s-alist dired-subdir-alist
) dir m-alist
)
2380 (setq dir
(car (car s-alist
))
2381 s-alist
(cdr s-alist
))
2382 (and (or kill-root
(not (string-equal dir dirname
)))
2383 (dired-in-this-tree dir dirname
)
2384 (dired-goto-subdir dir
)
2385 (setq m-alist
(nconc (dired-kill-subdir remember-marks
) m-alist
))))
2388 (defun dired-insert-subdir-newpos (new-dir)
2389 ;; Find pos for new subdir, according to tree order.
2390 ;;(goto-char (point-max))
2391 (let ((alist dired-subdir-alist
) elt dir new-pos
)
2393 (setq elt
(car alist
)
2396 (if (dired-tree-lessp dir new-dir
)
2397 ;; Insert NEW-DIR after DIR
2398 (setq new-pos
(dired-get-subdir-max elt
)
2400 (goto-char new-pos
))
2401 ;; want a separating newline between subdirs
2407 (defun dired-insert-subdir-del (element)
2408 ;; Erase an already present subdir (given by ELEMENT) from buffer.
2409 ;; Move to that buffer position. Return a mark-alist.
2410 (let ((begin-marker (dired-get-subdir-min element
)))
2411 (goto-char begin-marker
)
2412 ;; Are at beginning of subdir (and inside it!). Now determine its end:
2413 (goto-char (dired-subdir-max))
2414 (or (eobp);; want a separating newline _between_ subdirs:
2417 (dired-remember-marks begin-marker
(point))
2418 (delete-region begin-marker
(point)))))
2420 (defun dired-insert-subdir-doinsert (dirname switches
)
2421 ;; Insert ls output after point.
2422 ;; Return the boundary of the inserted text (as list of BEG and END).
2424 (let ((begin (point)))
2425 (let ((dired-actual-switches
2427 dired-subdir-switches
2428 (dired-replace-in-string "R" "" dired-actual-switches
))))
2429 (if (equal dirname
(car (car (last dired-subdir-alist
))))
2430 ;; If doing the top level directory of the buffer,
2431 ;; redo it as specified in dired-directory.
2432 (dired-readin-insert)
2433 (dired-insert-directory dirname dired-actual-switches nil nil t
)))
2434 (list begin
(point)))))
2436 (defun dired-insert-subdir-doupdate (dirname elt beg-end
)
2437 ;; Point is at the correct subdir alist position for ELT,
2438 ;; BEG-END is the subdir-region (as list of begin and end).
2439 (if elt
; subdir was already present
2440 ;; update its position (should actually be unchanged)
2441 (set-marker (dired-get-subdir-min elt
) (point-marker))
2442 (dired-alist-add dirname
(point-marker)))
2443 ;; The hook may depend on the subdir-alist containing the just
2444 ;; inserted subdir, so run it after dired-alist-add:
2445 (if dired-after-readin-hook
2447 (let ((begin (nth 0 beg-end
))
2448 (end (nth 1 beg-end
)))
2451 (narrow-to-region begin end
)
2452 ;; hook may add or delete lines, but the subdir boundary
2454 (run-hooks 'dired-after-readin-hook
))))))
2456 (defun dired-tree-lessp (dir1 dir2
)
2457 ;; Lexicographic order on file name components, like `ls -lR':
2458 ;; DIR1 < DIR2 if DIR1 comes *before* DIR2 in an `ls -lR' listing,
2459 ;; i.e., if DIR1 is a (grand)parent dir of DIR2,
2460 ;; or DIR1 and DIR2 are in the same parentdir and their last
2461 ;; components are string-lessp.
2462 ;; Thus ("/usr/" "/usr/bin") and ("/usr/a/" "/usr/b/") are tree-lessp.
2463 ;; string-lessp could arguably be replaced by file-newer-than-file-p
2464 ;; if dired-actual-switches contained t.
2465 (setq dir1
(file-name-as-directory dir1
)
2466 dir2
(file-name-as-directory dir2
))
2467 (let ((components-1 (dired-split "/" dir1
))
2468 (components-2 (dired-split "/" dir2
)))
2469 (while (and components-1
2471 (equal (car components-1
) (car components-2
)))
2472 (setq components-1
(cdr components-1
)
2473 components-2
(cdr components-2
)))
2474 (let ((c1 (car components-1
))
2475 (c2 (car components-2
)))
2478 (string-lessp c1 c2
))
2479 ((and (null c1
) (null c2
))
2480 nil
) ; they are equal, not lessp
2481 ((null c1
) ; c2 is a subdir of c1: c1<c2
2483 ((null c2
) ; c1 is a subdir of c2: c1>c2
2485 (t (error "This can't happen"))))))
2487 ;; There should be a builtin split function - inverse to mapconcat.
2488 (defun dired-split (pat str
&optional limit
)
2489 "Splitting on regexp PAT, turn string STR into a list of substrings.
2490 Optional third arg LIMIT (>= 1) is a limit to the length of the
2492 Thus, if SEP is a regexp that only matches itself,
2494 (mapconcat 'identity (dired-split SEP STRING) SEP)
2496 is always equal to STRING."
2497 (let* ((start (string-match pat str
))
2498 (result (list (substring str
0 start
)))
2500 (end (if start
(match-end 0))))
2501 (if end
; else nothing left
2502 (while (and (or (not (integerp limit
))
2504 (string-match pat str end
))
2505 (setq start
(match-beginning 0)
2507 result
(cons (substring str end start
) result
)
2511 (if (and (or (not (integerp limit
))
2513 end
) ; else nothing left
2515 (cons (substring str end
) result
)))
2518 ;;; moving by subdirectories
2521 (defun dired-prev-subdir (arg &optional no-error-if-not-found no-skip
)
2522 "Go to previous subdirectory, regardless of level.
2523 When called interactively and not on a subdir line, go to this subdir's line."
2526 (list (if current-prefix-arg
2527 (prefix-numeric-value current-prefix-arg
)
2528 ;; if on subdir start already, don't stay there!
2529 (if (dired-get-subdir) 1 0))))
2530 (dired-next-subdir (- arg
) no-error-if-not-found no-skip
))
2532 (defun dired-subdir-min ()
2534 (if (not (dired-prev-subdir 0 t t
))
2535 (error "Not in a subdir!")
2539 (defun dired-goto-subdir (dir)
2540 "Go to end of header line of DIR in this dired buffer.
2541 Return value of point on success, otherwise return nil.
2542 The next char is either \\n, or \\r if DIR is hidden."
2544 (prog1 ; let push-mark display its message
2545 (list (expand-file-name
2546 (completing-read "Goto in situ directory: " ; prompt
2547 dired-subdir-alist
; table
2550 (dired-current-directory))))
2552 (setq dir
(file-name-as-directory dir
))
2553 (let ((elt (assoc dir dired-subdir-alist
)))
2555 (goto-char (dired-get-subdir-min elt
))
2556 ;; dired-subdir-hidden-p and dired-add-entry depend on point being
2557 ;; at either \r or \n after this function succeeds.
2558 (progn (skip-chars-forward "^\r\n")
2562 (defun dired-mark-subdir-files ()
2563 "Mark all files except `.' and `..' in current subdirectory.
2564 If the Dired buffer shows multiple directories, this command
2565 marks the files listed in the subdirectory that point is in."
2567 (let ((p-min (dired-subdir-min)))
2568 (dired-mark-files-in-region p-min
(dired-subdir-max))))
2571 (defun dired-kill-subdir (&optional remember-marks
)
2572 "Remove all lines of current subdirectory.
2573 Lower levels are unaffected."
2574 ;; With optional REMEMBER-MARKS, return a mark-alist.
2576 (let* ((beg (dired-subdir-min))
2577 (end (dired-subdir-max))
2578 (modflag (buffer-modified-p))
2579 (cur-dir (dired-current-directory))
2580 (cons (assoc-string cur-dir dired-switches-alist
))
2582 (when (equal cur-dir
(expand-file-name default-directory
))
2583 (error "Attempt to kill top level directory"))
2585 (if remember-marks
(dired-remember-marks beg end
))
2586 (delete-region beg end
)
2587 (if (eobp) ; don't leave final blank line
2589 (dired-unsubdir cur-dir
)
2591 (setq dired-switches-alist
(delete cons dired-switches-alist
)))
2592 (restore-buffer-modified-p modflag
))))
2594 (defun dired-unsubdir (dir)
2595 ;; Remove DIR from the alist
2596 (setq dired-subdir-alist
2597 (delq (assoc dir dired-subdir-alist
) dired-subdir-alist
)))
2600 (defun dired-tree-up (arg)
2601 "Go up ARG levels in the dired tree."
2603 (let ((dir (dired-current-directory)))
2606 dir
(file-name-directory (directory-file-name dir
))))
2607 ;;(setq dir (expand-file-name dir))
2608 (or (dired-goto-subdir dir
)
2609 (error "Cannot go up to %s - not in this tree" dir
))))
2612 (defun dired-tree-down ()
2613 "Go down in the dired tree."
2615 (let ((dir (dired-current-directory)) ; has slash
2616 pos case-fold-search
) ; filenames are case sensitive
2617 (let ((rest (reverse dired-subdir-alist
)) elt
)
2619 (setq elt
(car rest
)
2621 (if (dired-in-this-tree (directory-file-name (car elt
)) dir
)
2623 pos
(dired-goto-subdir (car elt
))))))
2626 (error "At the bottom"))))
2630 (defun dired-unhide-subdir ()
2631 (let (buffer-read-only)
2632 (subst-char-in-region (dired-subdir-min) (dired-subdir-max) ?
\r ?
\n)))
2634 (defun dired-hide-check ()
2635 (or selective-display
2636 (error "selective-display must be t for subdir hiding to work!")))
2638 (defun dired-subdir-hidden-p (dir)
2639 (and selective-display
2641 (dired-goto-subdir dir
)
2642 (looking-at-p "\r"))))
2645 (defun dired-hide-subdir (arg)
2646 "Hide or unhide the current subdirectory and move to next directory.
2647 Optional prefix arg is a repeat factor.
2648 Use \\[dired-hide-all] to (un)hide all directories."
2651 (let ((modflag (buffer-modified-p)))
2652 (while (>= (setq arg
(1- arg
)) 0)
2653 (let* ((cur-dir (dired-current-directory))
2654 (hidden-p (dired-subdir-hidden-p cur-dir
))
2655 (elt (assoc cur-dir dired-subdir-alist
))
2656 (end-pos (1- (dired-get-subdir-max elt
)))
2658 ;; keep header line visible, hide rest
2659 (goto-char (dired-get-subdir-min elt
))
2660 (skip-chars-forward "^\n\r")
2662 (subst-char-in-region (point) end-pos ?
\r ?
\n)
2663 (subst-char-in-region (point) end-pos ?
\n ?
\r)))
2664 (dired-next-subdir 1 t
))
2665 (restore-buffer-modified-p modflag
)))
2668 (defun dired-hide-all (&optional ignored
)
2669 "Hide all subdirectories, leaving only their header lines.
2670 If there is already something hidden, make everything visible again.
2671 Use \\[dired-hide-subdir] to (un)hide a particular subdirectory."
2674 (let ((modflag (buffer-modified-p))
2677 (goto-char (point-min))
2678 (search-forward "\r" nil t
))
2679 ;; unhide - bombs on \r in filenames
2680 (subst-char-in-region (point-min) (point-max) ?
\r ?
\n)
2682 (let ((pos (point-max)) ; pos of end of last directory
2683 (alist dired-subdir-alist
))
2684 (while alist
; while there are dirs before pos
2685 (subst-char-in-region (dired-get-subdir-min (car alist
)) ; pos of prev dir
2687 (goto-char pos
) ; current dir
2688 ;; we're somewhere on current dir's line
2692 (setq pos
(dired-get-subdir-min (car alist
))) ; prev dir gets current dir
2693 (setq alist
(cdr alist
)))))
2694 (restore-buffer-modified-p modflag
)))
2696 ;;;###end dired-ins.el
2699 ;; Search only in file names in the Dired buffer.
2701 (defcustom dired-isearch-filenames nil
2702 "Non-nil to Isearch in file names only.
2703 If t, Isearch in Dired always matches only file names.
2704 If `dwim', Isearch matches file names when initial point position is on
2705 a file name. Otherwise, it searches the whole buffer without restrictions."
2706 :type
'(choice (const :tag
"No restrictions" nil
)
2707 (const :tag
"When point is on a file name initially, search file names" dwim
)
2708 (const :tag
"Always search in file names" t
))
2712 (define-minor-mode dired-isearch-filenames-mode
2713 "Toggle file names searching on or off.
2714 When on, Isearch skips matches outside file names using the predicate
2715 `dired-isearch-filter-filenames' that matches only at file names.
2716 When off, it uses the original predicate."
2718 (if dired-isearch-filenames-mode
2719 (add-function :before-while
(local 'isearch-filter-predicate
)
2720 #'dired-isearch-filter-filenames
2721 '((isearch-message-prefix .
"filename ")))
2722 (remove-function (local 'isearch-filter-predicate
)
2723 #'dired-isearch-filter-filenames
))
2725 (setq isearch-success t isearch-adjusted t
)
2729 (defun dired-isearch-filenames-setup ()
2730 "Set up isearch to search in Dired file names.
2731 Intended to be added to `isearch-mode-hook'."
2732 (when (or (eq dired-isearch-filenames t
)
2733 (and (eq dired-isearch-filenames
'dwim
)
2734 (get-text-property (point) 'dired-filename
)))
2735 (define-key isearch-mode-map
"\M-sff" 'dired-isearch-filenames-mode
)
2736 (dired-isearch-filenames-mode 1)
2737 (add-hook 'isearch-mode-end-hook
'dired-isearch-filenames-end nil t
)))
2739 (defun dired-isearch-filenames-end ()
2740 "Clean up the Dired file name search after terminating isearch."
2741 (define-key isearch-mode-map
"\M-sff" nil
)
2742 (dired-isearch-filenames-mode -
1)
2743 (remove-hook 'isearch-mode-end-hook
'dired-isearch-filenames-end t
))
2745 (defun dired-isearch-filter-filenames (beg end
)
2746 "Test whether the current search hit is a file name.
2747 Return non-nil if the text from BEG to END is part of a file
2748 name (has the text property `dired-filename')."
2749 (text-property-not-all (min beg end
) (max beg end
)
2750 'dired-filename nil
))
2753 (defun dired-isearch-filenames ()
2754 "Search for a string using Isearch only in file names in the Dired buffer."
2756 (let ((dired-isearch-filenames t
))
2757 (isearch-forward nil t
)))
2760 (defun dired-isearch-filenames-regexp ()
2761 "Search for a regexp using Isearch only in file names in the Dired buffer."
2763 (let ((dired-isearch-filenames t
))
2764 (isearch-forward-regexp nil t
)))
2767 ;; Functions for searching in tags style among marked files.
2770 (defun dired-do-isearch ()
2771 "Search for a string through all marked files using Isearch."
2773 (multi-isearch-files
2774 (dired-get-marked-files nil nil
'dired-nondirectory-p
)))
2777 (defun dired-do-isearch-regexp ()
2778 "Search for a regexp through all marked files using Isearch."
2780 (multi-isearch-files-regexp
2781 (dired-get-marked-files nil nil
'dired-nondirectory-p
)))
2784 (defun dired-do-search (regexp)
2785 "Search through all marked files for a match for REGEXP.
2786 Stops when a match is found.
2787 To continue searching for next match, use command \\[tags-loop-continue]."
2788 (interactive "sSearch marked files (regexp): ")
2789 (tags-search regexp
'(dired-get-marked-files nil nil
'dired-nondirectory-p
)))
2792 (defun dired-do-query-replace-regexp (from to
&optional delimited
)
2793 "Do `query-replace-regexp' of FROM with TO, on all marked files.
2794 Third arg DELIMITED (prefix arg) means replace only word-delimited matches.
2795 If you exit (\\[keyboard-quit], RET or q), you can resume the query replace
2796 with the command \\[tags-loop-continue]."
2799 (query-replace-read-args
2800 "Query replace regexp in marked files" t t
)))
2801 (list (nth 0 common
) (nth 1 common
) (nth 2 common
))))
2802 (dolist (file (dired-get-marked-files nil nil
'dired-nondirectory-p
))
2803 (let ((buffer (get-file-buffer file
)))
2804 (if (and buffer
(with-current-buffer buffer
2806 (error "File `%s' is visited read-only" file
))))
2807 (tags-query-replace from to delimited
2808 '(dired-get-marked-files nil nil
'dired-nondirectory-p
)))
2810 (declare-function xref--show-xrefs
"xref")
2811 (declare-function xref-query-replace-in-results
"xref")
2814 (defun dired-do-find-regexp (regexp)
2815 "Find all matches for REGEXP in all marked files.
2816 For any marked directory, all of its files are searched recursively.
2817 However, files matching `grep-find-ignored-files' and subdirectories
2818 matching `grep-find-ignored-directories' are skipped in the marked
2821 REGEXP should use constructs supported by your local `grep' command."
2822 (interactive "sSearch marked files (regexp): ")
2824 (defvar grep-find-ignored-files
)
2825 (defvar grep-find-ignored-directories
)
2826 (let* ((files (dired-get-marked-files))
2827 (ignores (nconc (mapcar
2828 (lambda (s) (concat s
"/"))
2829 grep-find-ignored-directories
)
2830 grep-find-ignored-files
))
2833 (xref-collect-matches regexp
"*" file
2834 (and (file-directory-p file
)
2838 (user-error "No matches for: %s" regexp
))
2839 (xref--show-xrefs xrefs nil t
)))
2842 (defun dired-do-find-regexp-and-replace (from to
)
2843 "Replace matches of FROM with TO, in all marked files.
2844 For any marked directory, matches in all of its files are replaced,
2845 recursively. However, files matching `grep-find-ignored-files'
2846 and subdirectories matching `grep-find-ignored-directories' are skipped
2847 in the marked directories.
2849 REGEXP should use constructs supported by your local `grep' command."
2852 (query-replace-read-args
2853 "Query replace regexp in marked files" t t
)))
2854 (list (nth 0 common
) (nth 1 common
))))
2855 (with-current-buffer (dired-do-find-regexp from
)
2856 (xref-query-replace-in-results from to
)))
2858 (defun dired-nondirectory-p (file)
2859 (not (file-directory-p file
)))
2862 (defun dired-show-file-type (file &optional deref-symlinks
)
2863 "Print the type of FILE, according to the `file' command.
2864 If you give a prefix to this command, and FILE is a symbolic
2865 link, then the type of the file linked to by FILE is printed
2867 (interactive (list (dired-get-filename t
) current-prefix-arg
))
2868 (let (process-file-side-effects)
2871 (process-file "file" nil t t
"-L" "--" file
)
2872 (process-file "file" nil t t
"--" file
))
2874 (backward-delete-char 1))
2875 (message "%s" (buffer-string)))))
2877 (provide 'dired-aux
)
2880 ;; byte-compile-dynamic: t
2881 ;; generated-autoload-file: "dired-loaddefs.el"
2884 ;;; dired-aux.el ends here