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