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