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