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