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