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