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