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