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