Use GConf and GSettings both, check GConf/GSettings toolbar style and font name.
[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
RS
701(defun dired-kill-line (&optional arg)
702 (interactive "P")
703 (setq arg (prefix-numeric-value arg))
704 (let (buffer-read-only file)
705 (while (/= 0 arg)
706 (setq file (dired-get-filename nil t))
707 (if (not file)
55535639 708 (error "Can only kill file lines")
dd87891b
RS
709 (save-excursion (and file
710 (dired-goto-subdir file)
711 (dired-kill-subdir)))
9b026d9f 712 (delete-region (line-beginning-position)
dd87891b
RS
713 (progn (forward-line 1) (point)))
714 (if (> arg 0)
715 (setq arg (1- arg))
716 (setq arg (1+ arg))
717 (forward-line -1))))
718 (dired-move-to-filename)))
719
720;;;###autoload
721(defun dired-do-kill-lines (&optional arg fmt)
722 "Kill all marked lines (not the files).
6482fcac 723With a prefix argument, kill that many lines starting with the current line.
769d9ed6
LT
724\(A negative argument kills backward.)
725If you use this command with a prefix argument to kill the line
726for a file that is a directory, which you have inserted in the
727Dired buffer as a subdirectory, then it deletes that subdirectory
728from the buffer as well.
729To kill an entire subdirectory \(without killing its line in the
730parent directory), go to its directory header line and use this
731command with a prefix argument (the value does not matter)."
dd87891b
RS
732 ;; Returns count of killed lines. FMT="" suppresses message.
733 (interactive "P")
6482fcac
RS
734 (if arg
735 (if (dired-get-subdir)
736 (dired-kill-subdir)
737 (dired-kill-line arg))
738 (save-excursion
739 (goto-char (point-min))
769d9ed6
LT
740 (let (buffer-read-only
741 (count 0)
742 (regexp (dired-marker-regexp)))
743 (while (and (not (eobp))
744 (re-search-forward regexp nil t))
745 (setq count (1+ count))
9b026d9f 746 (delete-region (line-beginning-position)
769d9ed6 747 (progn (forward-line 1) (point))))
6482fcac
RS
748 (or (equal "" fmt)
749 (message (or fmt "Killed %d line%s.") count (dired-plural-s count)))
750 count))))
dd87891b
RS
751
752;;;###end dired-cmd.el
83fadedf 753\f
dd87891b
RS
754;;; 30K
755;;;###begin dired-cp.el
756
757(defun dired-compress ()
758 ;; Compress or uncompress the current file.
759 ;; Return nil for success, offending filename else.
760 (let* (buffer-read-only
bfe81e78
RS
761 (from-file (dired-get-filename))
762 (new-file (dired-compress-file from-file)))
763 (if new-file
53a05194
RS
764 (let ((start (point)))
765 ;; Remove any preexisting entry for the name NEW-FILE.
766 (condition-case nil
767 (dired-remove-entry new-file)
768 (error nil))
769 (goto-char start)
770 ;; Now replace the current line with an entry for NEW-FILE.
771 (dired-update-file-line new-file) nil)
bfe81e78
RS
772 (dired-log (concat "Failed to compress" from-file))
773 from-file)))
774
077d5283
RS
775(defvar dired-compress-file-suffixes
776 '(("\\.gz\\'" "" "gunzip")
777 ("\\.tgz\\'" ".tar" "gunzip")
778 ("\\.Z\\'" "" "uncompress")
779 ;; For .z, try gunzip. It might be an old gzip file,
780 ;; or it might be from compact? pack? (which?) but gunzip handles both.
781 ("\\.z\\'" "" "gunzip")
999bd52a
JL
782 ("\\.dz\\'" "" "dictunzip")
783 ("\\.tbz\\'" ".tar" "bunzip2")
2d938ce7 784 ("\\.bz2\\'" "" "bunzip2")
470bce7d 785 ("\\.xz\\'" "" "unxz")
077d5283
RS
786 ;; This item controls naming for compression.
787 ("\\.tar\\'" ".tgz" nil))
788 "Control changes in file name suffixes for compression and uncompression.
789Each element specifies one transformation rule, and has the form:
790 (REGEXP NEW-SUFFIX PROGRAM)
791The rule applies when the old file name matches REGEXP.
792The new file name is computed by deleting the part that matches REGEXP
793 (as well as anything after that), then adding NEW-SUFFIX in its place.
794If PROGRAM is non-nil, the rule is an uncompression rule,
795and uncompression is done by running PROGRAM.
796Otherwise, the rule is a compression rule, and compression is done with gzip.")
797
d443f37c 798;;;###autoload
bfe81e78
RS
799(defun dired-compress-file (file)
800 ;; Compress or uncompress FILE.
801 ;; Return the name of the compressed or uncompressed file.
eb8c3be9 802 ;; Return nil if no change in files.
077d5283
RS
803 (let ((handler (find-file-name-handler file 'dired-compress-file))
804 suffix newname
805 (suffixes dired-compress-file-suffixes))
806 ;; See if any suffix rule matches this file name.
807 (while suffixes
808 (let (case-fold-search)
809 (if (string-match (car (car suffixes)) file)
810 (setq suffix (car suffixes) suffixes nil))
811 (setq suffixes (cdr suffixes))))
812 ;; If so, compute desired new name.
edb8d73e 813 (if suffix
077d5283
RS
814 (setq newname (concat (substring file 0 (match-beginning 0))
815 (nth 1 suffix))))
bfe81e78
RS
816 (cond (handler
817 (funcall handler 'dired-compress-file file))
818 ((file-symlink-p file)
819 nil)
077d5283
RS
820 ((and suffix (nth 2 suffix))
821 ;; We found an uncompression rule.
53a05194 822 (if (not (dired-check-process (concat "Uncompressing " file)
077d5283
RS
823 (nth 2 suffix) file))
824 newname))
dd87891b 825 (t
077d5283 826 ;;; We don't recognize the file as compressed, so compress it.
e251a1fd
RS
827 ;;; Try gzip; if we don't have that, use compress.
828 (condition-case nil
c8068734
CY
829 (let ((out-name (concat file ".gz")))
830 (and (or (not (file-exists-p out-name))
831 (y-or-n-p
9aea757b
CY
832 (format "File %s already exists. Really compress? "
833 out-name)))
c8068734
CY
834 (not (dired-check-process (concat "Compressing " file)
835 "gzip" "-f" file))
836 (or (file-exists-p out-name)
837 (setq out-name (concat file ".z")))
838 ;; Rename the compressed file to NEWNAME
839 ;; if it hasn't got that name already.
840 (if (and newname (not (equal newname out-name)))
841 (progn
842 (rename-file out-name newname t)
843 newname)
844 out-name)))
e251a1fd
RS
845 (file-error
846 (if (not (dired-check-process (concat "Compressing " file)
847 "compress" "-f" file))
077d5283 848 ;; Don't use NEWNAME with `compress'.
e251a1fd 849 (concat file ".Z"))))))))
83fadedf 850\f
dd87891b
RS
851(defun dired-mark-confirm (op-symbol arg)
852 ;; Request confirmation from the user that the operation described
853 ;; by OP-SYMBOL is to be performed on the marked files.
854 ;; Confirmation consists in a y-or-n question with a file list
855 ;; pop-up unless OP-SYMBOL is a member of `dired-no-confirm'.
856 ;; The files used are determined by ARG (as in dired-get-marked-files).
7baff557
SM
857 (or (eq dired-no-confirm t)
858 (memq op-symbol dired-no-confirm)
c232fd12
RS
859 ;; Pass t for DISTINGUISH-ONE-MARKED so that a single file which
860 ;; is marked pops up a window. That will help the user see
861 ;; it isn't the current line file.
862 (let ((files (dired-get-marked-files t arg nil t))
2de735de
RS
863 (string (if (eq op-symbol 'compress) "Compress or uncompress"
864 (capitalize (symbol-name op-symbol)))))
dd87891b 865 (dired-mark-pop-up nil op-symbol files (function y-or-n-p)
2de735de 866 (concat string " "
dd87891b
RS
867 (dired-mark-prompt arg files) "? ")))))
868
869(defun dired-map-over-marks-check (fun arg op-symbol &optional show-progress)
870; "Map FUN over marked files (with second ARG like in dired-map-over-marks)
871; and display failures.
872
873; FUN takes zero args. It returns non-nil (the offending object, e.g.
874; the short form of the filename) for a failure and probably logs a
875; detailed error explanation using function `dired-log'.
876
877; OP-SYMBOL is a symbol describing the operation performed (e.g.
878; `compress'). It is used with `dired-mark-pop-up' to prompt the user
879; (e.g. with `Compress * [2 files]? ') and to display errors (e.g.
880; `Failed to compress 1 of 2 files - type W to see why ("foo")')
881
882; SHOW-PROGRESS if non-nil means redisplay dired after each file."
883 (if (dired-mark-confirm op-symbol arg)
884 (let* ((total-list;; all of FUN's return values
885 (dired-map-over-marks (funcall fun) arg show-progress))
886 (total (length total-list))
887 (failures (delq nil total-list))
2de735de
RS
888 (count (length failures))
889 (string (if (eq op-symbol 'compress) "Compress or uncompress"
890 (capitalize (symbol-name op-symbol)))))
dd87891b
RS
891 (if (not failures)
892 (message "%s: %d file%s."
2de735de 893 string total (dired-plural-s total))
dd87891b
RS
894 ;; end this bunch of errors:
895 (dired-log-summary
896 (format "Failed to %s %d of %d file%s"
2de735de 897 (downcase string) count total (dired-plural-s total))
dd87891b
RS
898 failures)))))
899
05dcf18a 900;;;###autoload
3ef01959
CY
901(defun dired-query (sym prompt &rest args)
902 "Format PROMPT with ARGS, query user, and store the result in SYM.
903The return value is either nil or t.
904
905The user may type y or SPC to accept once; n or DEL to skip once;
906! to accept this and subsequent queries; or q or ESC to decline
907this and subsequent queries.
908
909If SYM is already bound to a non-nil value, this function may
910return automatically without querying the user. If SYM is !,
911return t; if SYM is q or ESC, return nil."
912 (let* ((char (symbol-value sym))
913 (char-choices '(?y ?\s ?n ?\177 ?! ?q ?\e)))
914 (cond ((eq char ?!)
915 t) ; accept, and don't ask again
916 ((memq char '(?q ?\e))
917 nil) ; skip, and don't ask again
918 (t ; no previous answer - ask now
919 (setq prompt
920 (concat (apply 'format prompt args)
921 (if help-form
922 (format " [Type yn!q or %s] "
923 (key-description
924 (char-to-string help-char)))
925 " [Type y, n, q or !] ")))
926 (set sym (setq char (read-char-choice prompt char-choices)))
927 (if (memq char '(?y ?\s ?!)) t)))))
928
83fadedf 929\f
dd87891b
RS
930;;;###autoload
931(defun dired-do-compress (&optional arg)
932 "Compress or uncompress marked (or next ARG) files."
933 (interactive "P")
934 (dired-map-over-marks-check (function dired-compress) arg 'compress t))
935
936;; Commands for Emacs Lisp files - load and byte compile
937
938(defun dired-byte-compile ()
939 ;; Return nil for success, offending file name else.
940 (let* ((filename (dired-get-filename))
123ec94d 941 elc-file buffer-read-only failure)
dd87891b
RS
942 (condition-case err
943 (save-excursion (byte-compile-file filename))
944 (error
945 (setq failure err)))
123ec94d 946 (setq elc-file (byte-compile-dest-file filename))
d5b876ef
RS
947 (or (file-exists-p elc-file)
948 (setq failure t))
dd87891b
RS
949 (if failure
950 (progn
951 (dired-log "Byte compile error for %s:\n%s\n" filename failure)
952 (dired-make-relative filename))
953 (dired-remove-file elc-file)
954 (forward-line) ; insert .elc after its .el file
955 (dired-add-file elc-file)
956 nil)))
957
958;;;###autoload
959(defun dired-do-byte-compile (&optional arg)
960 "Byte compile marked (or next ARG) Emacs Lisp files."
961 (interactive "P")
962 (dired-map-over-marks-check (function dired-byte-compile) arg 'byte-compile t))
963
964(defun dired-load ()
965 ;; Return nil for success, offending file name else.
966 (let ((file (dired-get-filename)) failure)
967 (condition-case err
968 (load file nil nil t)
969 (error (setq failure err)))
970 (if (not failure)
971 nil
972 (dired-log "Load error for %s:\n%s\n" file failure)
973 (dired-make-relative file))))
974
975;;;###autoload
976(defun dired-do-load (&optional arg)
977 "Load the marked (or next ARG) Emacs Lisp files."
978 (interactive "P")
979 (dired-map-over-marks-check (function dired-load) arg 'load t))
980
981;;;###autoload
982(defun dired-do-redisplay (&optional arg test-for-subdir)
983 "Redisplay all marked (or next ARG) files.
984If on a subdir line, redisplay that subdirectory. In that case,
79d123ad
LT
985a prefix arg lets you edit the `ls' switches used for the new listing.
986
987Dired remembers switches specified with a prefix arg, so that reverting
988the buffer will not reset them. However, using `dired-undo' to re-insert
989or delete subdirectories can bypass this machinery. Hence, you sometimes
990may have to reset some subdirectory switches after a `dired-undo'.
991You can reset all subdirectory switches to the default using
fad9e9b4 992\\<dired-mode-map>\\[dired-reset-subdir-switches].
098c61f2 993See Info node `(emacs)Subdir switches' for more details."
dd87891b
RS
994 ;; Moves point if the next ARG files are redisplayed.
995 (interactive "P\np")
996 (if (and test-for-subdir (dired-get-subdir))
f2260f48
LT
997 (let* ((dir (dired-get-subdir))
998 (switches (cdr (assoc-string dir dired-switches-alist))))
999 (dired-insert-subdir
1000 dir
1001 (when arg
1002 (read-string "Switches for listing: "
1003 (or switches
1004 dired-subdir-switches
1005 dired-actual-switches)))))
dd87891b
RS
1006 (message "Redisplaying...")
1007 ;; message much faster than making dired-map-over-marks show progress
00aa3651
RS
1008 (dired-uncache
1009 (if (consp dired-directory) (car dired-directory) dired-directory))
86a6e8e0
LL
1010 (dired-map-over-marks (let ((fname (dired-get-filename))
1011 ;; Postphone readin hook till we map
1012 ;; over all marked files (Bug#6810).
1013 (dired-after-readin-hook nil))
dd87891b
RS
1014 (message "Redisplaying... %s" fname)
1015 (dired-update-file-line fname))
1016 arg)
86a6e8e0 1017 (run-hooks 'dired-after-readin-hook)
dd87891b
RS
1018 (dired-move-to-filename)
1019 (message "Redisplaying...done")))
79d123ad
LT
1020
1021(defun dired-reset-subdir-switches ()
1022 "Set `dired-switches-alist' to nil and revert dired buffer."
1023 (interactive)
1024 (setq dired-switches-alist nil)
1025 (revert-buffer))
83fadedf 1026\f
dd87891b
RS
1027(defun dired-update-file-line (file)
1028 ;; Delete the current line, and insert an entry for FILE.
1029 ;; If FILE is nil, then just delete the current line.
1030 ;; Keeps any marks that may be present in column one (doing this
1031 ;; here is faster than with dired-add-entry's optional arg).
1032 ;; Does not update other dired buffers. Use dired-relist-entry for that.
edb57480
SB
1033 (let* ((opoint (line-beginning-position))
1034 (char (char-after opoint))
1035 (buffer-read-only))
9b026d9f 1036 (delete-region opoint (progn (forward-line 1) (point)))
dd87891b
RS
1037 (if file
1038 (progn
24193f35 1039 (dired-add-entry file nil t)
dd87891b
RS
1040 ;; Replace space by old marker without moving point.
1041 ;; Faster than goto+insdel inside a save-excursion?
1042 (subst-char-in-region opoint (1+ opoint) ?\040 char))))
1043 (dired-move-to-filename))
1044
d443f37c 1045;;;###autoload
dd87891b
RS
1046(defun dired-add-file (filename &optional marker-char)
1047 (dired-fun-in-all-buffers
b2a59df0 1048 (file-name-directory filename) (file-name-nondirectory filename)
dd87891b
RS
1049 (function dired-add-entry) filename marker-char))
1050
30abce25
GM
1051(defvar dired-omit-mode)
1052(declare-function dired-omit-regexp "dired-x" ())
1053(defvar dired-omit-localp)
1054
24193f35 1055(defun dired-add-entry (filename &optional marker-char relative)
30abce25
GM
1056 "Add a new dired entry for FILENAME.
1057Optionally mark it with MARKER-CHAR (a character, else uses
1058`dired-marker-char'). Note that this adds the entry `out of order'
1059if files are sorted by time, etc.
1060Skips files that match `dired-trivial-filenames'.
1061Exposes hidden subdirectories if a file is added there.
1062
1063If `dired-x' is loaded and `dired-omit-mode' is enabled, skips
1064files matching `dired-omit-regexp'."
1065 (if (or (not (featurep 'dired-x))
1066 (not dired-omit-mode)
1067 ;; Avoid calling ls for files that are going to be omitted anyway.
1068 (let ((omit-re (dired-omit-regexp)))
1069 (or (string= omit-re "")
1070 (not (string-match omit-re
1071 (cond
1072 ((eq 'no-dir dired-omit-localp)
1073 filename)
1074 ((eq t dired-omit-localp)
1075 (dired-make-relative filename))
1076 (t
1077 (dired-make-absolute
1078 filename
1079 (file-name-directory filename)))))))))
1080 ;; Do it!
1081 (progn
1082 (setq filename (directory-file-name filename))
1083 ;; Entry is always for files, even if they happen to also be directories
1084 (let* ((opoint (point))
1085 (cur-dir (dired-current-directory))
30abce25
GM
1086 (directory (if relative cur-dir (file-name-directory filename)))
1087 reason)
1088 (setq filename
1089 (if relative
1090 (file-relative-name filename directory)
1091 (file-name-nondirectory filename))
1092 reason
1093 (catch 'not-found
1094 (if (string= directory cur-dir)
1095 (progn
1096 (skip-chars-forward "^\r\n")
1097 (if (eq (following-char) ?\r)
1098 (dired-unhide-subdir))
1099 ;; We are already where we should be, except when
1100 ;; point is before the subdir line or its total line.
1101 (let ((p (dired-after-subdir-garbage cur-dir)))
1102 (if (< (point) p)
1103 (goto-char p))))
1104 ;; else try to find correct place to insert
1105 (if (dired-goto-subdir directory)
1106 (progn ;; unhide if necessary
1107 (if (looking-at "\r")
1108 ;; Point is at end of subdir line.
1109 (dired-unhide-subdir))
1110 ;; found - skip subdir and `total' line
1111 ;; and uninteresting files like . and ..
1112 ;; This better not move into the next subdir!
1113 (dired-goto-next-nontrivial-file))
1114 ;; not found
1115 (throw 'not-found "Subdir not found")))
1116 (let (buffer-read-only opoint)
1117 (beginning-of-line)
1118 (setq opoint (point))
1119 ;; Don't expand `.'.
1120 ;; Show just the file name within directory.
1121 (let ((default-directory directory))
1122 (dired-insert-directory
1123 directory
1124 (concat dired-actual-switches " -d")
1125 (list filename)))
1126 (goto-char opoint)
1127 ;; Put in desired marker char.
1128 (when marker-char
1129 (let ((dired-marker-char
1130 (if (integerp marker-char) marker-char
1131 dired-marker-char)))
1132 (dired-mark nil)))
1133 ;; Compensate for a bug in ange-ftp.
1134 ;; It inserts the file's absolute name, rather than
1135 ;; the relative one. That may be hard to fix since it
1136 ;; is probably controlled by something in ftp.
1137 (goto-char opoint)
1138 (let ((inserted-name (dired-get-filename 'verbatim)))
1139 (if (file-name-directory inserted-name)
1140 (let (props)
1141 (end-of-line)
1142 (forward-char (- (length inserted-name)))
1143 (setq props (text-properties-at (point)))
1144 (delete-char (length inserted-name))
1145 (let ((pt (point)))
1146 (insert filename)
1147 (set-text-properties pt (point) props))
1148 (forward-char 1))
1149 (forward-line 1)))
1150 (forward-line -1)
1151 (if dired-after-readin-hook
1152 ;; The subdir-alist is not affected...
1153 (save-excursion ; ...so we can run it right now:
1154 (save-restriction
1155 (beginning-of-line)
1156 (narrow-to-region (point)
1157 (line-beginning-position 2))
1158 (run-hooks 'dired-after-readin-hook))))
1159 (dired-move-to-filename))
1160 ;; return nil if all went well
1161 nil))
1162 (if reason ; don't move away on failure
1163 (goto-char opoint))
1164 (not reason))) ; return t on success, nil else
1165 ;; Don't do it (dired-omit-mode).
1166 ;; Return t for success (perhaps we should return file-exists-p).
1167 t))
dd87891b 1168
dd87891b
RS
1169(defun dired-after-subdir-garbage (dir)
1170 ;; Return pos of first file line of DIR, skipping header and total
1171 ;; or wildcard lines.
1172 ;; Important: never moves into the next subdir.
1173 ;; DIR is assumed to be unhidden.
dd87891b
RS
1174 (save-excursion
1175 (or (dired-goto-subdir dir) (error "This cannot happen"))
1176 (forward-line 1)
1177 (while (and (not (eolp)) ; don't cross subdir boundary
1178 (not (dired-move-to-filename)))
1179 (forward-line 1))
1180 (point)))
1181
d443f37c 1182;;;###autoload
dd87891b
RS
1183(defun dired-remove-file (file)
1184 (dired-fun-in-all-buffers
b2a59df0
RS
1185 (file-name-directory file) (file-name-nondirectory file)
1186 (function dired-remove-entry) file))
dd87891b
RS
1187
1188(defun dired-remove-entry (file)
1189 (save-excursion
1190 (and (dired-goto-file file)
1191 (let (buffer-read-only)
1192 (delete-region (progn (beginning-of-line) (point))
9b026d9f 1193 (line-beginning-position 2))))))
dd87891b 1194
d443f37c 1195;;;###autoload
dd87891b 1196(defun dired-relist-file (file)
e5369aad 1197 "Create or update the line for FILE in all Dired buffers it would belong in."
dd87891b 1198 (dired-fun-in-all-buffers (file-name-directory file)
b2a59df0 1199 (file-name-nondirectory file)
dd87891b
RS
1200 (function dired-relist-entry) file))
1201
1202(defun dired-relist-entry (file)
1203 ;; Relist the line for FILE, or just add it if it did not exist.
57dabf6b 1204 ;; FILE must be an absolute file name.
dd87891b
RS
1205 (let (buffer-read-only marker)
1206 ;; If cursor is already on FILE's line delete-region will cause
1207 ;; save-excursion to fail because of floating makers,
1208 ;; moving point to beginning of line. Sigh.
1209 (save-excursion
1210 (and (dired-goto-file file)
1211 (delete-region (progn (beginning-of-line)
1212 (setq marker (following-char))
1213 (point))
9b026d9f 1214 (line-beginning-position 2)))
dd87891b
RS
1215 (setq file (directory-file-name file))
1216 (dired-add-entry file (if (eq ?\040 marker) nil marker)))))
83fadedf 1217\f
dd87891b
RS
1218;;; Copy, move/rename, making hard and symbolic links
1219
91a7e829 1220(defcustom dired-backup-overwrite nil
9201cc28 1221 "Non-nil if Dired should ask about making backups before overwriting files.
91a7e829
RS
1222Special value `always' suppresses confirmation."
1223 :type '(choice (const :tag "off" nil)
1224 (const :tag "suppress" always)
a9e9b8fa 1225 (other :tag "ask" t))
91a7e829 1226 :group 'dired)
dd87891b 1227
bf0de14d
CY
1228;; This is a fluid var used in dired-handle-overwrite. It should be
1229;; let-bound whenever dired-copy-file etc are called. See
1230;; dired-create-files for an example.
1231(defvar dired-overwrite-confirmed)
6482fcac 1232
dd87891b 1233(defun dired-handle-overwrite (to)
e5369aad 1234 ;; Save old version of file TO that is to be overwritten.
6482fcac 1235 ;; `dired-overwrite-confirmed' and `overwrite-backup-query' are fluid vars
dd87891b 1236 ;; from dired-create-files.
d63a6ae0 1237 (let (backup)
bbfe2308
CY
1238 (when (and dired-backup-overwrite
1239 dired-overwrite-confirmed
1240 (setq backup (car (find-backup-file-name to)))
1241 (or (eq 'always dired-backup-overwrite)
1242 (dired-query 'overwrite-backup-query
1243 "Make backup for existing file `%s'? "
1244 to)))
1245 (rename-file to backup 0) ; confirm overwrite of old backup
1246 (dired-relist-entry backup))))
dd87891b 1247
d443f37c 1248;;;###autoload
dd87891b
RS
1249(defun dired-copy-file (from to ok-flag)
1250 (dired-handle-overwrite to)
c62a8073
RS
1251 (dired-copy-file-recursive from to ok-flag dired-copy-preserve-time t
1252 dired-recursive-copies))
dd87891b 1253
8e845e23
JB
1254(declare-function make-symbolic-link "fileio.c")
1255
ba1acd68
RS
1256(defun dired-copy-file-recursive (from to ok-flag &optional
1257 preserve-time top recursive)
06b60517 1258 (let ((attrs (file-attributes from)))
3b68c506
RS
1259 (if (and recursive
1260 (eq t (car attrs))
1261 (or (eq recursive 'always)
ce5a3ac0 1262 (yes-or-no-p (format "Recursive copies of %s? " from))))
3b68c506 1263 ;; This is a directory.
06b60517 1264 (copy-directory from to preserve-time)
3b68c506
RS
1265 ;; Not a directory.
1266 (or top (dired-handle-overwrite to))
c62a8073
RS
1267 (condition-case err
1268 (if (stringp (car attrs))
1269 ;; It is a symlink
1270 (make-symbolic-link (car attrs) to ok-flag)
06b60517 1271 (copy-file from to ok-flag preserve-time))
4a725859 1272 (file-date-error
c62a8073
RS
1273 (push (dired-make-relative from)
1274 dired-create-files-failures)
7a547817 1275 (dired-log "Can't set date on %s:\n%s\n" from err))))))
ba1acd68 1276
d443f37c 1277;;;###autoload
e5369aad
RS
1278(defun dired-rename-file (file newname ok-if-already-exists)
1279 (dired-handle-overwrite newname)
1280 (rename-file file newname ok-if-already-exists) ; error is caught in -create-files
dd87891b 1281 ;; Silently rename the visited file of any buffer visiting this file.
e5369aad
RS
1282 (and (get-file-buffer file)
1283 (with-current-buffer (get-file-buffer file)
1284 (set-visited-file-name newname nil t)))
1285 (dired-remove-file file)
dd87891b 1286 ;; See if it's an inserted subdir, and rename that, too.
e5369aad 1287 (dired-rename-subdir file newname))
dd87891b
RS
1288
1289(defun dired-rename-subdir (from-dir to-dir)
1290 (setq from-dir (file-name-as-directory from-dir)
1291 to-dir (file-name-as-directory to-dir))
b2a59df0 1292 (dired-fun-in-all-buffers from-dir nil
dd87891b
RS
1293 (function dired-rename-subdir-1) from-dir to-dir)
1294 ;; Update visited file name of all affected buffers
9df38cef
RS
1295 (let ((expanded-from-dir (expand-file-name from-dir))
1296 (blist (buffer-list)))
dd87891b 1297 (while blist
7fdbcd83 1298 (with-current-buffer (car blist)
dd87891b 1299 (if (and buffer-file-name
9df38cef 1300 (dired-in-this-tree buffer-file-name expanded-from-dir))
dd87891b 1301 (let ((modflag (buffer-modified-p))
83fadedf 1302 (to-file (dired-replace-in-string
dd87891b
RS
1303 (concat "^" (regexp-quote from-dir))
1304 to-dir
1305 buffer-file-name)))
1306 (set-visited-file-name to-file)
1307 (set-buffer-modified-p modflag))))
1308 (setq blist (cdr blist)))))
1309
1310(defun dired-rename-subdir-1 (dir to)
1311 ;; Rename DIR to TO in headerlines and dired-subdir-alist, if DIR or
1312 ;; one of its subdirectories is expanded in this buffer.
9df38cef
RS
1313 (let ((expanded-dir (expand-file-name dir))
1314 (alist dired-subdir-alist)
dd87891b
RS
1315 (elt nil))
1316 (while alist
1317 (setq elt (car alist)
1318 alist (cdr alist))
9df38cef 1319 (if (dired-in-this-tree (car elt) expanded-dir)
dd87891b
RS
1320 ;; ELT's subdir is affected by the rename
1321 (dired-rename-subdir-2 elt dir to)))
1322 (if (equal dir default-directory)
1323 ;; if top level directory was renamed, lots of things have to be
1324 ;; updated:
1325 (progn
1326 (dired-unadvertise dir) ; we no longer dired DIR...
1327 (setq default-directory to
1328 dired-directory (expand-file-name;; this is correct
1329 ;; with and without wildcards
1330 (file-name-nondirectory dired-directory)
1331 to))
1332 (let ((new-name (file-name-nondirectory
1333 (directory-file-name dired-directory))))
1334 ;; try to rename buffer, but just leave old name if new
1335 ;; name would already exist (don't try appending "<%d>")
1336 (or (get-buffer new-name)
1337 (rename-buffer new-name)))
1338 ;; ... we dired TO now:
1339 (dired-advertise)))))
1340
1341(defun dired-rename-subdir-2 (elt dir to)
f2260f48
LT
1342 ;; Update the headerline and dired-subdir-alist element, as well as
1343 ;; dired-switches-alist element, of directory described by
1344 ;; alist-element ELT to reflect the moving of DIR to TO. Thus, ELT
1345 ;; describes either DIR itself or a subdir of DIR.
dd87891b
RS
1346 (save-excursion
1347 (let ((regexp (regexp-quote (directory-file-name dir)))
1348 (newtext (directory-file-name to))
1349 buffer-read-only)
1350 (goto-char (dired-get-subdir-min elt))
1351 ;; Update subdir headerline in buffer
1352 (if (not (looking-at dired-subdir-regexp))
1353 (error "%s not found where expected - dired-subdir-alist broken?"
1354 dir)
1355 (goto-char (match-beginning 1))
1356 (if (re-search-forward regexp (match-end 1) t)
1357 (replace-match newtext t t)
1358 (error "Expected to find `%s' in headerline of %s" dir (car elt))))
f2260f48
LT
1359 ;; Update buffer-local dired-subdir-alist and dired-switches-alist
1360 (let ((cons (assoc-string (car elt) dired-switches-alist))
1361 (cur-dir (dired-normalize-subdir
1362 (dired-replace-in-string regexp newtext (car elt)))))
1363 (setcar elt cur-dir)
1364 (when cons (setcar cons cur-dir))))))
83fadedf 1365\f
06b60517
JB
1366;; Bound in dired-create-files
1367(defvar overwrite-query)
1368(defvar overwrite-backup-query)
1369
dd87891b
RS
1370;; The basic function for half a dozen variations on cp/mv/ln/ln -s.
1371(defun dired-create-files (file-creator operation fn-list name-constructor
1372 &optional marker-char)
0d9e9a12
CY
1373 "Create one or more new files from a list of existing files FN-LIST.
1374This function also handles querying the user, updating Dired
1375buffers, and displaying a success or failure message.
dd87891b 1376
0d9e9a12
CY
1377FILE-CREATOR should be a function. It is called once for each
1378file in FN-LIST, and must create a new file, querying the user
1379and updating Dired buffers as necessary. It should accept three
1380arguments: the old file name, the new name, and an argument
1381OK-IF-ALREADY-EXISTS with the same meaning as in `copy-file'.
dd87891b 1382
0d9e9a12
CY
1383OPERATION should be a capitalized string describing the operation
1384performed (e.g. `Copy'). It is used for error logging.
dd87891b 1385
0d9e9a12 1386FN-LIST is the list of files to copy (full absolute file names).
dd87891b 1387
0d9e9a12
CY
1388NAME-CONSTRUCTOR should be a function accepting a single
1389argument, the name of an old file, and returning either the
1390corresponding new file name or nil to skip.
dd87891b 1391
0d9e9a12
CY
1392Optional MARKER-CHAR is a character with which to mark every
1393newfile's entry, or t to use the current marker character if the
1394old file was marked."
c62a8073
RS
1395 (let (dired-create-files-failures failures
1396 skipped (success-count 0) (total (length fn-list)))
dd87891b
RS
1397 (let (to overwrite-query
1398 overwrite-backup-query) ; for dired-handle-overwrite
04509548
SM
1399 (dolist (from fn-list)
1400 (setq to (funcall name-constructor from))
1401 (if (equal to from)
1402 (progn
1403 (setq to nil)
1404 (dired-log "Cannot %s to same file: %s\n"
1405 (downcase operation) from)))
1406 (if (not to)
1407 (setq skipped (cons (dired-make-relative from) skipped))
1408 (let* ((overwrite (file-exists-p to))
1409 (dired-overwrite-confirmed ; for dired-handle-overwrite
1410 (and overwrite
1411 (let ((help-form '(format "\
dd87891b
RS
1412Type SPC or `y' to overwrite file `%s',
1413DEL or `n' to skip to next,
1414ESC or `q' to not overwrite any of the remaining files,
1415`!' to overwrite all remaining files with no more questions." to)))
04509548
SM
1416 (dired-query 'overwrite-query
1417 "Overwrite `%s'?" to))))
1418 ;; must determine if FROM is marked before file-creator
1419 ;; gets a chance to delete it (in case of a move).
1420 (actual-marker-char
1421 (cond ((integerp marker-char) marker-char)
1422 (marker-char (dired-file-marker from)) ; slow
1423 (t nil))))
9de31df2
TV
1424 (when (and (file-directory-p from)
1425 (file-directory-p to)
1426 (eq file-creator 'dired-copy-file))
1427 (setq to (file-name-directory to)))
04509548
SM
1428 (condition-case err
1429 (progn
1430 (funcall file-creator from to dired-overwrite-confirmed)
1431 (if overwrite
1432 ;; If we get here, file-creator hasn't been aborted
1433 ;; and the old entry (if any) has to be deleted
1434 ;; before adding the new entry.
1435 (dired-remove-file to))
1436 (setq success-count (1+ success-count))
1437 (message "%s: %d of %d" operation success-count total)
1438 (dired-add-file to actual-marker-char))
1439 (file-error ; FILE-CREATOR aborted
1440 (progn
1441 (push (dired-make-relative from)
1442 failures)
1443 (dired-log "%s `%s' to `%s' failed:\n%s\n"
1444 operation from to err))))))))
dd87891b 1445 (cond
c62a8073
RS
1446 (dired-create-files-failures
1447 (setq failures (nconc failures dired-create-files-failures))
1448 (dired-log-summary
1449 (format "%s failed for %d file%s in %d requests"
1450 operation (length failures)
1451 (dired-plural-s (length failures))
1452 total)
1453 failures))
dd87891b
RS
1454 (failures
1455 (dired-log-summary
1456 (format "%s failed for %d of %d file%s"
c62a8073
RS
1457 operation (length failures)
1458 total (dired-plural-s total))
dd87891b
RS
1459 failures))
1460 (skipped
1461 (dired-log-summary
1462 (format "%s: %d of %d file%s skipped"
1463 operation (length skipped) total
1464 (dired-plural-s total))
1465 skipped))
1466 (t
1467 (message "%s: %s file%s"
1468 operation success-count (dired-plural-s success-count)))))
1469 (dired-move-to-filename))
83fadedf 1470\f
dd87891b 1471(defun dired-do-create-files (op-symbol file-creator operation arg
616e14f4
SM
1472 &optional marker-char op1
1473 how-to)
1474 "Create a new file for each marked file.
1475Prompts user for target, which is a directory in which to create
9c8f194d 1476 the new files. Target may also be a plain file if only one marked
dcaf31d3
EZ
1477 file exists. The way the default for the target directory is
1478 computed depends on the value of `dired-dwim-target-directory'.
616e14f4
SM
1479OP-SYMBOL is the symbol for the operation. Function `dired-mark-pop-up'
1480 will determine whether pop-ups are appropriate for this OP-SYMBOL.
1481FILE-CREATOR and OPERATION as in `dired-create-files'.
1482ARG as in `dired-get-marked-files'.
1483Optional arg MARKER-CHAR as in `dired-create-files'.
1484Optional arg OP1 is an alternate form for OPERATION if there is
1485 only one file.
9c8f194d
CY
1486Optional arg HOW-TO determiness how to treat the target.
1487 If HOW-TO is nil, use `file-directory-p' to determine if the
1488 target is a directory. If so, the marked file(s) are created
1489 inside that directory. Otherwise, the target is a plain file;
1490 an error is raised unless there is exactly one marked file.
1491 If HOW-TO is t, target is always treated as a plain file.
1492 Otherwise, HOW-TO should be a function of one argument, TARGET.
1493 If its return value is nil, TARGET is regarded as a plain file.
1494 If it return value is a list, TARGET is a generalized
1495 directory (e.g. some sort of archive). The first element of
1496 this list must be a function with at least four arguments:
1497 operation - as OPERATION above.
1498 rfn-list - list of the relative names for the marked files.
1499 fn-list - list of the absolute names for the marked files.
1500 target - the name of the target itself.
616e14f4 1501 The rest of into-dir are optional arguments.
9c8f194d 1502 For any other return value, TARGET is treated as a directory."
dd87891b
RS
1503 (or op1 (setq op1 operation))
1504 (let* ((fn-list (dired-get-marked-files nil arg))
ba1acd68
RS
1505 (rfn-list (mapcar (function dired-make-relative) fn-list))
1506 (dired-one-file ; fluid variable inside dired-create-files
1507 (and (consp fn-list) (null (cdr fn-list)) (car fn-list)))
75ab0c79
GM
1508 (target-dir (dired-dwim-target-directory))
1509 (default (and dired-one-file
1510 (expand-file-name (file-name-nondirectory (car fn-list))
1511 target-dir)))
e237085f 1512 (defaults (dired-dwim-target-defaults fn-list target-dir))
ba1acd68 1513 (target (expand-file-name ; fluid variable inside dired-create-files
e237085f
JL
1514 (minibuffer-with-setup-hook
1515 (lambda ()
1516 (set (make-local-variable 'minibuffer-default-add-function) nil)
1517 (setq minibuffer-default defaults))
1518 (dired-mark-read-file-name
1519 (concat (if dired-one-file op1 operation) " %s to: ")
1520 target-dir op-symbol arg rfn-list default))))
325fec3c
EZ
1521 (into-dir (cond ((null how-to)
1522 ;; Allow DOS/Windows users to change the letter
1523 ;; case of a directory. If we don't test these
1524 ;; conditions up front, file-directory-p below
1525 ;; will return t because the filesystem is
1526 ;; case-insensitive, and Emacs will try to move
1527 ;; foo -> foo/foo, which fails.
c60ee5e7 1528 (if (and (memq system-type '(ms-dos windows-nt cygwin))
325fec3c
EZ
1529 (eq op-symbol 'move)
1530 dired-one-file
1531 (string= (downcase
1532 (expand-file-name (car fn-list)))
1533 (downcase
1534 (expand-file-name target)))
1535 (not (string=
1536 (file-name-nondirectory (car fn-list))
1537 (file-name-nondirectory target))))
1538 nil
1539 (file-directory-p target)))
dd87891b
RS
1540 ((eq how-to t) nil)
1541 (t (funcall how-to target)))))
ba1acd68
RS
1542 (if (and (consp into-dir) (functionp (car into-dir)))
1543 (apply (car into-dir) operation rfn-list fn-list target (cdr into-dir))
1544 (if (not (or dired-one-file into-dir))
1545 (error "Marked %s: target must be a directory: %s" operation target))
1546 ;; rename-file bombs when moving directories unless we do this:
1547 (or into-dir (setq target (directory-file-name target)))
1548 (dired-create-files
1549 file-creator operation fn-list
1550 (if into-dir ; target is a directory
1551 ;; This function uses fluid variable target when called
1552 ;; inside dired-create-files:
1553 (function
1554 (lambda (from)
1555 (expand-file-name (file-name-nondirectory from) target)))
06b60517 1556 (function (lambda (_from) target)))
ba1acd68 1557 marker-char))))
dd87891b
RS
1558
1559;; Read arguments for a marked-files command that wants a file name,
1560;; perhaps popping up the list of marked files.
1561;; ARG is the prefix arg and indicates whether the files came from
1562;; marks (ARG=nil) or a repeat factor (integerp ARG).
1563;; If the current file was used, the list has but one element and ARG
1564;; does not matter. (It is non-nil, non-integer in that case, namely '(4)).
64666d2d
MB
1565;; DEFAULT is the default value to return if the user just hits RET;
1566;; if it is omitted or nil, then the name of the directory is used.
dd87891b 1567
64666d2d
MB
1568(defun dired-mark-read-file-name (prompt dir op-symbol arg files
1569 &optional default)
dd87891b
RS
1570 (dired-mark-pop-up
1571 nil op-symbol files
1572 (function read-file-name)
64666d2d 1573 (format prompt (dired-mark-prompt arg files)) dir default))
dd87891b
RS
1574
1575(defun dired-dwim-target-directory ()
1576 ;; Try to guess which target directory the user may want.
e237085f
JL
1577 ;; If there is a dired buffer displayed in one of the next windows,
1578 ;; use its current subdir, else use current subdir of this dired buffer.
dd87891b
RS
1579 (let ((this-dir (and (eq major-mode 'dired-mode)
1580 (dired-current-directory))))
1581 ;; non-dired buffer may want to profit from this function, e.g. vm-uudecode
1582 (if dired-dwim-target
e237085f
JL
1583 (let* ((other-win (get-window-with-predicate
1584 (lambda (window)
1585 (with-current-buffer (window-buffer window)
1586 (eq major-mode 'dired-mode)))))
1587 (other-dir (and other-win
1588 (with-current-buffer (window-buffer other-win)
1589 (and (eq major-mode 'dired-mode)
1590 (dired-current-directory))))))
dd87891b
RS
1591 (or other-dir this-dir))
1592 this-dir)))
e237085f
JL
1593
1594(defun dired-dwim-target-defaults (fn-list target-dir)
1595 ;; Return a list of default values for file-reading functions in Dired.
1596 ;; This list may contain directories from Dired buffers in other windows.
1597 ;; `fn-list' is a list of file names used to build a list of defaults.
1598 ;; When nil or more than one element, a list of defaults will
1599 ;; contain only directory names. `target-dir' is a directory name
1600 ;; to exclude from the returned list, for the case when this
1601 ;; directory name is already presented in initial input.
1602 ;; For Dired operations that support `dired-dwim-target',
1603 ;; the argument `target-dir' should have the value returned
1604 ;; from `dired-dwim-target-directory'.
1605 (let ((dired-one-file
1606 (and (consp fn-list) (null (cdr fn-list)) (car fn-list)))
1607 (current-dir (and (eq major-mode 'dired-mode)
1608 (dired-current-directory)))
1609 dired-dirs)
1610 ;; Get a list of directories of visible buffers in dired-mode.
1611 (walk-windows (lambda (w)
1612 (with-current-buffer (window-buffer w)
1613 (and (eq major-mode 'dired-mode)
1614 (push (dired-current-directory) dired-dirs)))))
1615 ;; Force the current dir to be the first in the list.
1616 (setq dired-dirs
1617 (delete-dups (delq nil (cons current-dir (nreverse dired-dirs)))))
1618 ;; Remove the target dir (if specified) or the current dir from
1619 ;; default values, because it should be already in initial input.
1620 (setq dired-dirs (delete (or target-dir current-dir) dired-dirs))
1621 ;; Return a list of default values.
1622 (if dired-one-file
1623 ;; For one file operation, provide a list that contains
1624 ;; other directories, other directories with the appended filename
1625 ;; and the current directory with the appended filename, e.g.
1626 ;; 1. /TARGET-DIR/
1627 ;; 2. /TARGET-DIR/FILENAME
1628 ;; 3. /CURRENT-DIR/FILENAME
1629 (append dired-dirs
1630 (mapcar (lambda (dir)
1631 (expand-file-name
1632 (file-name-nondirectory (car fn-list)) dir))
1633 (reverse dired-dirs))
1634 (list (expand-file-name
1635 (file-name-nondirectory (car fn-list))
1636 (or target-dir current-dir))))
1637 ;; For multi-file operation, return only a list of other directories.
1638 dired-dirs)))
1639
83fadedf 1640\f
dd87891b
RS
1641;;;###autoload
1642(defun dired-create-directory (directory)
ff854b0b
CY
1643 "Create a directory called DIRECTORY.
1644If DIRECTORY already exists, signal an error."
dd87891b
RS
1645 (interactive
1646 (list (read-file-name "Create directory: " (dired-current-directory))))
934b4968
JL
1647 (let* ((expanded (directory-file-name (expand-file-name directory)))
1648 (try expanded) new)
ff854b0b
CY
1649 (if (file-exists-p expanded)
1650 (error "Cannot create directory %s: file exists" expanded))
934b4968
JL
1651 ;; Find the topmost nonexistent parent dir (variable `new')
1652 (while (and try (not (file-exists-p try)) (not (equal new try)))
1653 (setq new try
1654 try (directory-file-name (file-name-directory try))))
1655 (make-directory expanded t)
1656 (when new
1657 (dired-add-file new)
1658 (dired-move-to-filename))))
dd87891b
RS
1659
1660(defun dired-into-dir-with-symlinks (target)
1661 (and (file-directory-p target)
1662 (not (file-symlink-p target))))
1663;; This may not always be what you want, especially if target is your
1664;; home directory and it happens to be a symbolic link, as is often the
1665;; case with NFS and automounters. Or if you want to make symlinks
1666;; into directories that themselves are only symlinks, also quite
1667;; common.
1668
1669;; So we don't use this function as value for HOW-TO in
1670;; dired-do-symlink, which has the minor disadvantage of
1671;; making links *into* a symlinked-dir, when you really wanted to
1672;; *overwrite* that symlink. In that (rare, I guess) case, you'll
1673;; just have to remove that symlink by hand before making your marked
1674;; symlinks.
1675
ba1acd68 1676(defvar dired-copy-how-to-fn nil
5a0c3f56 1677 "Either nil or a function used by `dired-do-copy' to determine target.
ba1acd68
RS
1678See HOW-TO argument for `dired-do-create-files'.")
1679
dd87891b
RS
1680;;;###autoload
1681(defun dired-do-copy (&optional arg)
1682 "Copy all marked (or next ARG) files, or copy the current file.
1683This normally preserves the last-modified date when copying.
1684When operating on just the current file, you specify the new name.
b5458fc2
RS
1685When operating on multiple or marked files, you specify a directory,
1686and new copies of these files are made in that directory
dcaf31d3
EZ
1687with the same names that the files currently have. The default
1688suggested for the target directory depends on the value of
ec9581d5
RS
1689`dired-dwim-target', which see.
1690
1691This command copies symbolic links by creating new ones,
1692like `cp -d'."
dd87891b 1693 (interactive "P")
ea185644 1694 (let ((dired-recursive-copies dired-recursive-copies))
ba1acd68 1695 (dired-do-create-files 'copy (function dired-copy-file)
de97d5e8 1696 "Copy"
ea185644
GM
1697 arg dired-keep-marker-copy
1698 nil dired-copy-how-to-fn)))
dd87891b
RS
1699
1700;;;###autoload
1701(defun dired-do-symlink (&optional arg)
1702 "Make symbolic links to current file or all marked (or next ARG) files.
1703When operating on just the current file, you specify the new name.
1704When operating on multiple or marked files, you specify a directory
1705and new symbolic links are made in that directory
dcaf31d3
EZ
1706with the same names that the files currently have. The default
1707suggested for the target directory depends on the value of
806f34d6
EZ
1708`dired-dwim-target', which see.
1709
1710For relative symlinks, use \\[dired-do-relsymlink]."
dd87891b
RS
1711 (interactive "P")
1712 (dired-do-create-files 'symlink (function make-symbolic-link)
1713 "Symlink" arg dired-keep-marker-symlink))
1714
1715;;;###autoload
1716(defun dired-do-hardlink (&optional arg)
1717 "Add names (hard links) current file or all marked (or next ARG) files.
1718When operating on just the current file, you specify the new name.
1719When operating on multiple or marked files, you specify a directory
1720and new hard links are made in that directory
dcaf31d3
EZ
1721with the same names that the files currently have. The default
1722suggested for the target directory depends on the value of
1723`dired-dwim-target', which see."
dd87891b 1724 (interactive "P")
e5369aad 1725 (dired-do-create-files 'hardlink (function dired-hardlink)
dd87891b
RS
1726 "Hardlink" arg dired-keep-marker-hardlink))
1727
e5369aad
RS
1728(defun dired-hardlink (file newname &optional ok-if-already-exists)
1729 (dired-handle-overwrite newname)
1730 ;; error is caught in -create-files
1731 (add-name-to-file file newname ok-if-already-exists)
1732 ;; Update the link count
1733 (dired-relist-file file))
1734
dd87891b
RS
1735;;;###autoload
1736(defun dired-do-rename (&optional arg)
1737 "Rename current file or all marked (or next ARG) files.
1738When renaming just the current file, you specify the new name.
dcaf31d3 1739When renaming multiple or marked files, you specify a directory.
e5369aad 1740This command also renames any buffers that are visiting the files.
dcaf31d3
EZ
1741The default suggested for the target directory depends on the value
1742of `dired-dwim-target', which see."
dd87891b
RS
1743 (interactive "P")
1744 (dired-do-create-files 'move (function dired-rename-file)
1745 "Move" arg dired-keep-marker-rename "Rename"))
1746;;;###end dired-cp.el
83fadedf 1747\f
dd87891b
RS
1748;;; 5K
1749;;;###begin dired-re.el
06b60517
JB
1750(defvar rename-regexp-query)
1751
dd87891b 1752(defun dired-do-create-files-regexp
731ffbd9 1753 (file-creator operation arg regexp newname &optional whole-name marker-char)
dd87891b
RS
1754 ;; Create a new file for each marked file using regexps.
1755 ;; FILE-CREATOR and OPERATION as in dired-create-files.
1756 ;; ARG as in dired-get-marked-files.
1757 ;; Matches each marked file against REGEXP and constructs the new
1758 ;; filename from NEWNAME (like in function replace-match).
731ffbd9 1759 ;; Optional arg WHOLE-NAME means match/replace the whole file name
dd87891b
RS
1760 ;; instead of only the non-directory part of the file.
1761 ;; Optional arg MARKER-CHAR as in dired-create-files.
1762 (let* ((fn-list (dired-get-marked-files nil arg))
dd87891b
RS
1763 (operation-prompt (concat operation " `%s' to `%s'?"))
1764 (rename-regexp-help-form (format "\
1765Type SPC or `y' to %s one match, DEL or `n' to skip to next,
1766`!' to %s all remaining matches with no more questions."
1767 (downcase operation)
1768 (downcase operation)))
1769 (regexp-name-constructor
1770 ;; Function to construct new filename using REGEXP and NEWNAME:
731ffbd9 1771 (if whole-name ; easy (but rare) case
dd87891b
RS
1772 (function
1773 (lambda (from)
1774 (let ((to (dired-string-replace-match regexp from newname))
1775 ;; must bind help-form directly around call to
1776 ;; dired-query
1777 (help-form rename-regexp-help-form))
1778 (if to
1779 (and (dired-query 'rename-regexp-query
1780 operation-prompt
1781 from
1782 to)
1783 to)
1784 (dired-log "%s: %s did not match regexp %s\n"
1785 operation from regexp)))))
731ffbd9 1786 ;; not whole-name, replace non-directory part only
dd87891b
RS
1787 (function
1788 (lambda (from)
1789 (let* ((new (dired-string-replace-match
1790 regexp (file-name-nondirectory from) newname))
1791 (to (and new ; nil means there was no match
1792 (expand-file-name new
1793 (file-name-directory from))))
1794 (help-form rename-regexp-help-form))
1795 (if to
1796 (and (dired-query 'rename-regexp-query
1797 operation-prompt
1798 (dired-make-relative from)
1799 (dired-make-relative to))
1800 to)
1801 (dired-log "%s: %s did not match regexp %s\n"
1802 operation (file-name-nondirectory from) regexp)))))))
1803 rename-regexp-query)
1804 (dired-create-files
1805 file-creator operation fn-list regexp-name-constructor marker-char)))
1806
1807(defun dired-mark-read-regexp (operation)
1808 ;; Prompt user about performing OPERATION.
731ffbd9
KS
1809 ;; Read and return list of: regexp newname arg whole-name.
1810 (let* ((whole-name
dd87891b
RS
1811 (equal 0 (prefix-numeric-value current-prefix-arg)))
1812 (arg
731ffbd9 1813 (if whole-name nil current-prefix-arg))
dd87891b
RS
1814 (regexp
1815 (dired-read-regexp
731ffbd9 1816 (concat (if whole-name "Abs. " "") operation " from (regexp): ")))
dd87891b
RS
1817 (newname
1818 (read-string
731ffbd9
KS
1819 (concat (if whole-name "Abs. " "") operation " " regexp " to: "))))
1820 (list regexp newname arg whole-name)))
dd87891b
RS
1821
1822;;;###autoload
731ffbd9 1823(defun dired-do-rename-regexp (regexp newname &optional arg whole-name)
2b3e941a
EZ
1824 "Rename selected files whose names match REGEXP to NEWNAME.
1825
1826With non-zero prefix argument ARG, the command operates on the next ARG
1827files. Otherwise, it operates on all the marked files, or the current
1828file if none are marked.
1829
dd87891b
RS
1830As each match is found, the user must type a character saying
1831 what to do with it. For directions, type \\[help-command] at that time.
1832NEWNAME may contain \\=\\<n> or \\& as in `query-replace-regexp'.
1833REGEXP defaults to the last regexp used.
57dabf6b
RS
1834
1835With a zero prefix arg, renaming by regexp affects the absolute file name.
1836Normally, only the non-directory part of the file name is used and changed."
dd87891b
RS
1837 (interactive (dired-mark-read-regexp "Rename"))
1838 (dired-do-create-files-regexp
1839 (function dired-rename-file)
731ffbd9 1840 "Rename" arg regexp newname whole-name dired-keep-marker-rename))
dd87891b
RS
1841
1842;;;###autoload
731ffbd9 1843(defun dired-do-copy-regexp (regexp newname &optional arg whole-name)
2b3e941a 1844 "Copy selected files whose names match REGEXP to NEWNAME.
99c364e4 1845See function `dired-do-rename-regexp' for more info."
dd87891b 1846 (interactive (dired-mark-read-regexp "Copy"))
ba1acd68
RS
1847 (let ((dired-recursive-copies nil)) ; No recursive copies.
1848 (dired-do-create-files-regexp
1849 (function dired-copy-file)
1850 (if dired-copy-preserve-time "Copy [-p]" "Copy")
731ffbd9 1851 arg regexp newname whole-name dired-keep-marker-copy)))
dd87891b
RS
1852
1853;;;###autoload
731ffbd9 1854(defun dired-do-hardlink-regexp (regexp newname &optional arg whole-name)
2b3e941a 1855 "Hardlink selected files whose names match REGEXP to NEWNAME.
99c364e4 1856See function `dired-do-rename-regexp' for more info."
dd87891b
RS
1857 (interactive (dired-mark-read-regexp "HardLink"))
1858 (dired-do-create-files-regexp
1859 (function add-name-to-file)
731ffbd9 1860 "HardLink" arg regexp newname whole-name dired-keep-marker-hardlink))
dd87891b
RS
1861
1862;;;###autoload
731ffbd9 1863(defun dired-do-symlink-regexp (regexp newname &optional arg whole-name)
2b3e941a 1864 "Symlink selected files whose names match REGEXP to NEWNAME.
99c364e4 1865See function `dired-do-rename-regexp' for more info."
dd87891b
RS
1866 (interactive (dired-mark-read-regexp "SymLink"))
1867 (dired-do-create-files-regexp
1868 (function make-symbolic-link)
731ffbd9 1869 "SymLink" arg regexp newname whole-name dired-keep-marker-symlink))
dd87891b 1870
06b60517
JB
1871(defvar rename-non-directory-query)
1872
dd87891b
RS
1873(defun dired-create-files-non-directory
1874 (file-creator basename-constructor operation arg)
1875 ;; Perform FILE-CREATOR on the non-directory part of marked files
1876 ;; using function BASENAME-CONSTRUCTOR, with query for each file.
1877 ;; OPERATION like in dired-create-files, ARG as in dired-get-marked-files.
1878 (let (rename-non-directory-query)
1879 (dired-create-files
1880 file-creator
1881 operation
1882 (dired-get-marked-files nil arg)
1883 (function
1884 (lambda (from)
1885 (let ((to (concat (file-name-directory from)
1886 (funcall basename-constructor
1887 (file-name-nondirectory from)))))
1888 (and (let ((help-form (format "\
1889Type SPC or `y' to %s one file, DEL or `n' to skip to next,
1890`!' to %s all remaining matches with no more questions."
1891 (downcase operation)
1892 (downcase operation))))
1893 (dired-query 'rename-non-directory-query
1894 (concat operation " `%s' to `%s'")
1895 (dired-make-relative from)
1896 (dired-make-relative to)))
1897 to))))
1898 dired-keep-marker-rename)))
1899
1900(defun dired-rename-non-directory (basename-constructor operation arg)
1901 (dired-create-files-non-directory
1902 (function dired-rename-file)
1903 basename-constructor operation arg))
1904
1905;;;###autoload
1906(defun dired-upcase (&optional arg)
1907 "Rename all marked (or next ARG) files to upper case."
1908 (interactive "P")
1909 (dired-rename-non-directory (function upcase) "Rename upcase" arg))
1910
1911;;;###autoload
1912(defun dired-downcase (&optional arg)
1913 "Rename all marked (or next ARG) files to lower case."
1914 (interactive "P")
1915 (dired-rename-non-directory (function downcase) "Rename downcase" arg))
1916
1917;;;###end dired-re.el
83fadedf 1918\f
dd87891b
RS
1919;;; 13K
1920;;;###begin dired-ins.el
1921
1922;;;###autoload
1923(defun dired-maybe-insert-subdir (dirname &optional
1924 switches no-error-if-not-dir-p)
1925 "Insert this subdirectory into the same dired buffer.
1926If it is already present, just move to it (type \\[dired-do-redisplay] to refresh),
1927 else inserts it at its natural place (as `ls -lR' would have done).
1928With a prefix arg, you may edit the ls switches used for this listing.
1929 You can add `R' to the switches to expand the whole tree starting at
1930 this subdirectory.
79d123ad
LT
1931This function takes some pains to conform to `ls -lR' output.
1932
1933Dired remembers switches specified with a prefix arg, so that reverting
1934the buffer will not reset them. However, using `dired-undo' to re-insert
1935or delete subdirectories can bypass this machinery. Hence, you sometimes
1936may have to reset some subdirectory switches after a `dired-undo'.
1937You can reset all subdirectory switches to the default using
fad9e9b4 1938\\<dired-mode-map>\\[dired-reset-subdir-switches].
098c61f2 1939See Info node `(emacs)Subdir switches' for more details."
dd87891b
RS
1940 (interactive
1941 (list (dired-get-filename)
1942 (if current-prefix-arg
f2260f48
LT
1943 (read-string "Switches for listing: "
1944 (or dired-subdir-switches dired-actual-switches)))))
dd87891b
RS
1945 (let ((opoint (point)))
1946 ;; We don't need a marker for opoint as the subdir is always
1947 ;; inserted *after* opoint.
1948 (setq dirname (file-name-as-directory dirname))
1949 (or (and (not switches)
1950 (dired-goto-subdir dirname))
1951 (dired-insert-subdir dirname switches no-error-if-not-dir-p))
1952 ;; Push mark so that it's easy to find back. Do this after the
1953 ;; insert message so that the user sees the `Mark set' message.
1954 (push-mark opoint)))
1955
72af9867 1956;;;###autoload
dd87891b
RS
1957(defun dired-insert-subdir (dirname &optional switches no-error-if-not-dir-p)
1958 "Insert this subdirectory into the same dired buffer.
1959If it is already present, overwrites previous entry,
1960 else inserts it at its natural place (as `ls -lR' would have done).
1961With a prefix arg, you may edit the `ls' switches used for this listing.
1962 You can add `R' to the switches to expand the whole tree starting at
1963 this subdirectory.
1964This function takes some pains to conform to `ls -lR' output."
1965 ;; NO-ERROR-IF-NOT-DIR-P needed for special filesystems like
1966 ;; Prospero where dired-ls does the right thing, but
1967 ;; file-directory-p has not been redefined.
1968 (interactive
1969 (list (dired-get-filename)
1970 (if current-prefix-arg
f2260f48
LT
1971 (read-string "Switches for listing: "
1972 (or dired-subdir-switches dired-actual-switches)))))
dd87891b 1973 (setq dirname (file-name-as-directory (expand-file-name dirname)))
dd87891b
RS
1974 (or no-error-if-not-dir-p
1975 (file-directory-p dirname)
1976 (error "Attempt to insert a non-directory: %s" dirname))
1977 (let ((elt (assoc dirname dired-subdir-alist))
f2260f48
LT
1978 (cons (assoc-string dirname dired-switches-alist))
1979 (modflag (buffer-modified-p))
1980 (old-switches switches)
1981 switches-have-R mark-alist case-fold-search buffer-read-only)
1982 (and (not switches) cons (setq switches (cdr cons)))
1983 (dired-insert-subdir-validate dirname switches)
dd87891b
RS
1984 ;; case-fold-search is nil now, so we can test for capital `R':
1985 (if (setq switches-have-R (and switches (string-match "R" switches)))
1986 ;; avoid duplicated subdirs
1987 (setq mark-alist (dired-kill-tree dirname t)))
1988 (if elt
1989 ;; If subdir is already present, remove it and remember its marks
1990 (setq mark-alist (nconc (dired-insert-subdir-del elt) mark-alist))
1991 (dired-insert-subdir-newpos dirname)) ; else compute new position
1992 (dired-insert-subdir-doupdate
1993 dirname elt (dired-insert-subdir-doinsert dirname switches))
f2260f48
LT
1994 (when old-switches
1995 (if cons
1996 (setcdr cons switches)
1997 (push (cons dirname switches) dired-switches-alist)))
1998 (when switches-have-R
1999 (dired-build-subdir-alist switches)
081e4397 2000 (setq switches (dired-replace-in-string "R" "" switches))
f2260f48
LT
2001 (dolist (cur-ass dired-subdir-alist)
2002 (let ((cur-dir (car cur-ass)))
2003 (and (dired-in-this-tree cur-dir dirname)
f2260f48
LT
2004 (let ((cur-cons (assoc-string cur-dir dired-switches-alist)))
2005 (if cur-cons
2006 (setcdr cur-cons switches)
2007 (push (cons cur-dir switches) dired-switches-alist)))))))
dd87891b 2008 (dired-initial-position dirname)
f2260f48
LT
2009 (save-excursion (dired-mark-remembered mark-alist))
2010 (restore-buffer-modified-p modflag)))
dd87891b 2011
dd87891b
RS
2012(defun dired-insert-subdir-validate (dirname &optional switches)
2013 ;; Check that it is valid to insert DIRNAME with SWITCHES.
2014 ;; Signal an error if invalid (e.g. user typed `i' on `..').
d443f37c 2015 (or (dired-in-this-tree dirname (expand-file-name default-directory))
dd87891b 2016 (error "%s: not in this directory tree" dirname))
f2260f48
LT
2017 (let ((real-switches (or switches dired-subdir-switches)))
2018 (when real-switches
dd87891b
RS
2019 (let (case-fold-search)
2020 (mapcar
2021 (function
2022 (lambda (x)
f2260f48 2023 (or (eq (null (string-match x real-switches))
dd87891b 2024 (null (string-match x dired-actual-switches)))
f2260f48
LT
2025 (error
2026 "Can't have dirs with and without -%s switches together" x))))
dd87891b 2027 ;; all switches that make a difference to dired-get-filename:
f2260f48 2028 '("F" "b"))))))
dd87891b
RS
2029
2030(defun dired-alist-add (dir new-marker)
2031 ;; Add new DIR at NEW-MARKER. Sort alist.
2032 (dired-alist-add-1 dir new-marker)
2033 (dired-alist-sort))
2034
2035(defun dired-alist-sort ()
2036 ;; Keep the alist sorted on buffer position.
2037 (setq dired-subdir-alist
2038 (sort dired-subdir-alist
2039 (function (lambda (elt1 elt2)
2040 (> (dired-get-subdir-min elt1)
2041 (dired-get-subdir-min elt2)))))))
2042
0a07c3a9 2043(defun dired-kill-tree (dirname &optional remember-marks kill-root)
616e14f4 2044 "Kill all proper subdirs of DIRNAME, excluding DIRNAME itself.
0a07c3a9
LT
2045Interactively, you can kill DIRNAME as well by using a prefix argument.
2046In interactive use, the command prompts for DIRNAME.
2047
2048When called from Lisp, if REMEMBER-MARKS is non-nil, return an alist
2049of marked files. If KILL-ROOT is non-nil, kill DIRNAME as well."
2050 (interactive "DKill tree below directory: \ni\nP")
2051 (setq dirname (file-name-as-directory (expand-file-name dirname)))
dd87891b
RS
2052 (let ((s-alist dired-subdir-alist) dir m-alist)
2053 (while s-alist
2054 (setq dir (car (car s-alist))
2055 s-alist (cdr s-alist))
0a07c3a9
LT
2056 (and (or kill-root (not (string-equal dir dirname)))
2057 (dired-in-this-tree dir dirname)
2058 (dired-goto-subdir dir)
2059 (setq m-alist (nconc (dired-kill-subdir remember-marks) m-alist))))
dd87891b
RS
2060 m-alist))
2061
2062(defun dired-insert-subdir-newpos (new-dir)
2063 ;; Find pos for new subdir, according to tree order.
2064 ;;(goto-char (point-max))
2065 (let ((alist dired-subdir-alist) elt dir pos new-pos)
2066 (while alist
2067 (setq elt (car alist)
2068 alist (cdr alist)
06b60517 2069 dir (car elt))
dd87891b
RS
2070 (if (dired-tree-lessp dir new-dir)
2071 ;; Insert NEW-DIR after DIR
2072 (setq new-pos (dired-get-subdir-max elt)
2073 alist nil)))
2074 (goto-char new-pos))
2075 ;; want a separating newline between subdirs
2076 (or (eobp)
2077 (forward-line -1))
2078 (insert "\n")
2079 (point))
2080
2081(defun dired-insert-subdir-del (element)
2082 ;; Erase an already present subdir (given by ELEMENT) from buffer.
2083 ;; Move to that buffer position. Return a mark-alist.
2084 (let ((begin-marker (dired-get-subdir-min element)))
2085 (goto-char begin-marker)
2086 ;; Are at beginning of subdir (and inside it!). Now determine its end:
2087 (goto-char (dired-subdir-max))
2088 (or (eobp);; want a separating newline _between_ subdirs:
2089 (forward-char -1))
2090 (prog1
2091 (dired-remember-marks begin-marker (point))
2092 (delete-region begin-marker (point)))))
2093
2094(defun dired-insert-subdir-doinsert (dirname switches)
e5369aad 2095 ;; Insert ls output after point.
dd87891b 2096 ;; Return the boundary of the inserted text (as list of BEG and END).
349254d3
AS
2097 (save-excursion
2098 (let ((begin (point)))
349254d3
AS
2099 (let ((dired-actual-switches
2100 (or switches
f2260f48 2101 dired-subdir-switches
349254d3
AS
2102 (dired-replace-in-string "R" "" dired-actual-switches))))
2103 (if (equal dirname (car (car (last dired-subdir-alist))))
2104 ;; If doing the top level directory of the buffer,
2105 ;; redo it as specified in dired-directory.
2106 (dired-readin-insert)
2107 (dired-insert-directory dirname dired-actual-switches nil nil t)))
349254d3 2108 (list begin (point)))))
dd87891b
RS
2109
2110(defun dired-insert-subdir-doupdate (dirname elt beg-end)
2111 ;; Point is at the correct subdir alist position for ELT,
2112 ;; BEG-END is the subdir-region (as list of begin and end).
2113 (if elt ; subdir was already present
2114 ;; update its position (should actually be unchanged)
2115 (set-marker (dired-get-subdir-min elt) (point-marker))
2116 (dired-alist-add dirname (point-marker)))
2117 ;; The hook may depend on the subdir-alist containing the just
2118 ;; inserted subdir, so run it after dired-alist-add:
2119 (if dired-after-readin-hook
2120 (save-excursion
2121 (let ((begin (nth 0 beg-end))
2122 (end (nth 1 beg-end)))
2123 (goto-char begin)
2124 (save-restriction
2125 (narrow-to-region begin end)
2126 ;; hook may add or delete lines, but the subdir boundary
2127 ;; marker floats
2128 (run-hooks 'dired-after-readin-hook))))))
2129
2130(defun dired-tree-lessp (dir1 dir2)
57dabf6b 2131 ;; Lexicographic order on file name components, like `ls -lR':
4837b516
GM
2132 ;; DIR1 < DIR2 if DIR1 comes *before* DIR2 in an `ls -lR' listing,
2133 ;; i.e., if DIR1 is a (grand)parent dir of DIR2,
dd87891b
RS
2134 ;; or DIR1 and DIR2 are in the same parentdir and their last
2135 ;; components are string-lessp.
2136 ;; Thus ("/usr/" "/usr/bin") and ("/usr/a/" "/usr/b/") are tree-lessp.
2137 ;; string-lessp could arguably be replaced by file-newer-than-file-p
2138 ;; if dired-actual-switches contained `t'.
2139 (setq dir1 (file-name-as-directory dir1)
2140 dir2 (file-name-as-directory dir2))
2141 (let ((components-1 (dired-split "/" dir1))
2142 (components-2 (dired-split "/" dir2)))
2143 (while (and components-1
2144 components-2
2145 (equal (car components-1) (car components-2)))
2146 (setq components-1 (cdr components-1)
2147 components-2 (cdr components-2)))
2148 (let ((c1 (car components-1))
2149 (c2 (car components-2)))
2150
2151 (cond ((and c1 c2)
2152 (string-lessp c1 c2))
2153 ((and (null c1) (null c2))
2154 nil) ; they are equal, not lessp
2155 ((null c1) ; c2 is a subdir of c1: c1<c2
2156 t)
2157 ((null c2) ; c1 is a subdir of c2: c1>c2
2158 nil)
2159 (t (error "This can't happen"))))))
2160
2161;; There should be a builtin split function - inverse to mapconcat.
2162(defun dired-split (pat str &optional limit)
2163 "Splitting on regexp PAT, turn string STR into a list of substrings.
2164Optional third arg LIMIT (>= 1) is a limit to the length of the
2165resulting list.
2166Thus, if SEP is a regexp that only matches itself,
2167
2168 (mapconcat 'identity (dired-split SEP STRING) SEP)
2169
2170is always equal to STRING."
2171 (let* ((start (string-match pat str))
2172 (result (list (substring str 0 start)))
2173 (count 1)
2174 (end (if start (match-end 0))))
2175 (if end ; else nothing left
2176 (while (and (or (not (integerp limit))
2177 (< count limit))
2178 (string-match pat str end))
2179 (setq start (match-beginning 0)
2180 count (1+ count)
2181 result (cons (substring str end start) result)
2182 end (match-end 0)
2183 start end)
2184 ))
2185 (if (and (or (not (integerp limit))
2186 (< count limit))
2187 end) ; else nothing left
2188 (setq result
2189 (cons (substring str end) result)))
2190 (nreverse result)))
83fadedf 2191\f
dd87891b
RS
2192;;; moving by subdirectories
2193
dd87891b
RS
2194;;;###autoload
2195(defun dired-prev-subdir (arg &optional no-error-if-not-found no-skip)
2196 "Go to previous subdirectory, regardless of level.
2197When called interactively and not on a subdir line, go to this subdir's line."
2198 ;;(interactive "p")
2199 (interactive
2200 (list (if current-prefix-arg
2201 (prefix-numeric-value current-prefix-arg)
2202 ;; if on subdir start already, don't stay there!
2203 (if (dired-get-subdir) 1 0))))
2204 (dired-next-subdir (- arg) no-error-if-not-found no-skip))
2205
2206(defun dired-subdir-min ()
2207 (save-excursion
2208 (if (not (dired-prev-subdir 0 t t))
2209 (error "Not in a subdir!")
2210 (point))))
2211
2212;;;###autoload
2213(defun dired-goto-subdir (dir)
2214 "Go to end of header line of DIR in this dired buffer.
2215Return value of point on success, otherwise return nil.
2216The next char is either \\n, or \\r if DIR is hidden."
2217 (interactive
2218 (prog1 ; let push-mark display its message
2219 (list (expand-file-name
2220 (completing-read "Goto in situ directory: " ; prompt
2221 dired-subdir-alist ; table
2222 nil ; predicate
2223 t ; require-match
2224 (dired-current-directory))))
2225 (push-mark)))
2226 (setq dir (file-name-as-directory dir))
2227 (let ((elt (assoc dir dired-subdir-alist)))
2228 (and elt
2229 (goto-char (dired-get-subdir-min elt))
2230 ;; dired-subdir-hidden-p and dired-add-entry depend on point being
2231 ;; at either \r or \n after this function succeeds.
2232 (progn (skip-chars-forward "^\r\n")
2233 (point)))))
83fadedf 2234\f
dd87891b
RS
2235;;;###autoload
2236(defun dired-mark-subdir-files ()
472974e9
RS
2237 "Mark all files except `.' and `..' in current subdirectory.
2238If the Dired buffer shows multiple directories, this command
2239marks the files listed in the subdirectory that point is in."
96149b57 2240 (interactive)
dd87891b
RS
2241 (let ((p-min (dired-subdir-min)))
2242 (dired-mark-files-in-region p-min (dired-subdir-max))))
2243
2244;;;###autoload
2245(defun dired-kill-subdir (&optional remember-marks)
2246 "Remove all lines of current subdirectory.
2247Lower levels are unaffected."
2248 ;; With optional REMEMBER-MARKS, return a mark-alist.
2249 (interactive)
f2260f48
LT
2250 (let* ((beg (dired-subdir-min))
2251 (end (dired-subdir-max))
2252 (modflag (buffer-modified-p))
2253 (cur-dir (dired-current-directory))
2254 (cons (assoc-string cur-dir dired-switches-alist))
2255 buffer-read-only)
dd87891b
RS
2256 (if (equal cur-dir default-directory)
2257 (error "Attempt to kill top level directory"))
2258 (prog1
2259 (if remember-marks (dired-remember-marks beg end))
2260 (delete-region beg end)
2261 (if (eobp) ; don't leave final blank line
2262 (delete-char -1))
f2260f48
LT
2263 (dired-unsubdir cur-dir)
2264 (when cons
2265 (setq dired-switches-alist (delete cons dired-switches-alist)))
2266 (restore-buffer-modified-p modflag))))
dd87891b
RS
2267
2268(defun dired-unsubdir (dir)
2269 ;; Remove DIR from the alist
2270 (setq dired-subdir-alist
2271 (delq (assoc dir dired-subdir-alist) dired-subdir-alist)))
2272
2273;;;###autoload
2274(defun dired-tree-up (arg)
2275 "Go up ARG levels in the dired tree."
2276 (interactive "p")
2277 (let ((dir (dired-current-directory)))
2278 (while (>= arg 1)
2279 (setq arg (1- arg)
2280 dir (file-name-directory (directory-file-name dir))))
2281 ;;(setq dir (expand-file-name dir))
2282 (or (dired-goto-subdir dir)
55535639 2283 (error "Cannot go up to %s - not in this tree" dir))))
dd87891b
RS
2284
2285;;;###autoload
2286(defun dired-tree-down ()
2287 "Go down in the dired tree."
2288 (interactive)
2289 (let ((dir (dired-current-directory)) ; has slash
2290 pos case-fold-search) ; filenames are case sensitive
2291 (let ((rest (reverse dired-subdir-alist)) elt)
2292 (while rest
2293 (setq elt (car rest)
2294 rest (cdr rest))
2295 (if (dired-in-this-tree (directory-file-name (car elt)) dir)
2296 (setq rest nil
2297 pos (dired-goto-subdir (car elt))))))
2298 (if pos
2299 (goto-char pos)
2300 (error "At the bottom"))))
83fadedf 2301\f
dd87891b
RS
2302;;; hiding
2303
2304(defun dired-unhide-subdir ()
2305 (let (buffer-read-only)
2306 (subst-char-in-region (dired-subdir-min) (dired-subdir-max) ?\r ?\n)))
2307
2308(defun dired-hide-check ()
2309 (or selective-display
2310 (error "selective-display must be t for subdir hiding to work!")))
2311
2312(defun dired-subdir-hidden-p (dir)
2313 (and selective-display
2314 (save-excursion
2315 (dired-goto-subdir dir)
2316 (looking-at "\r"))))
2317
2318;;;###autoload
2319(defun dired-hide-subdir (arg)
2320 "Hide or unhide the current subdirectory and move to next directory.
2321Optional prefix arg is a repeat factor.
2322Use \\[dired-hide-all] to (un)hide all directories."
2323 (interactive "p")
2324 (dired-hide-check)
f2260f48
LT
2325 (let ((modflag (buffer-modified-p)))
2326 (while (>= (setq arg (1- arg)) 0)
2327 (let* ((cur-dir (dired-current-directory))
2328 (hidden-p (dired-subdir-hidden-p cur-dir))
2329 (elt (assoc cur-dir dired-subdir-alist))
2330 (end-pos (1- (dired-get-subdir-max elt)))
2331 buffer-read-only)
2332 ;; keep header line visible, hide rest
2333 (goto-char (dired-get-subdir-min elt))
2334 (skip-chars-forward "^\n\r")
2335 (if hidden-p
2336 (subst-char-in-region (point) end-pos ?\r ?\n)
2337 (subst-char-in-region (point) end-pos ?\n ?\r)))
2338 (dired-next-subdir 1 t))
2339 (restore-buffer-modified-p modflag)))
dd87891b
RS
2340
2341;;;###autoload
8ae41cbc 2342(defun dired-hide-all (&optional ignored)
dd87891b
RS
2343 "Hide all subdirectories, leaving only their header lines.
2344If there is already something hidden, make everything visible again.
2345Use \\[dired-hide-subdir] to (un)hide a particular subdirectory."
2346 (interactive "P")
2347 (dired-hide-check)
f2260f48
LT
2348 (let ((modflag (buffer-modified-p))
2349 buffer-read-only)
dd87891b
RS
2350 (if (save-excursion
2351 (goto-char (point-min))
2352 (search-forward "\r" nil t))
2353 ;; unhide - bombs on \r in filenames
2354 (subst-char-in-region (point-min) (point-max) ?\r ?\n)
2355 ;; hide
2356 (let ((pos (point-max)) ; pos of end of last directory
2357 (alist dired-subdir-alist))
f2260f48 2358 (while alist ; while there are dirs before pos
dd87891b
RS
2359 (subst-char-in-region (dired-get-subdir-min (car alist)) ; pos of prev dir
2360 (save-excursion
2361 (goto-char pos) ; current dir
2362 ;; we're somewhere on current dir's line
2363 (forward-line -1)
2364 (point))
2365 ?\n ?\r)
2366 (setq pos (dired-get-subdir-min (car alist))) ; prev dir gets current dir
f2260f48
LT
2367 (setq alist (cdr alist)))))
2368 (restore-buffer-modified-p modflag)))
dd87891b
RS
2369
2370;;;###end dired-ins.el
2f14b48d 2371
83fadedf 2372\f
b4b6bda2
JL
2373;; Search only in file names in the Dired buffer.
2374
2375(defcustom dired-isearch-filenames nil
9201cc28 2376 "Non-nil to Isearch in file names only.
b9d9c159
JL
2377If t, Isearch in Dired always matches only file names.
2378If `dwim', Isearch matches file names when initial point position is on
2379a file name. Otherwise, it searches the whole buffer without restrictions."
b4b6bda2 2380 :type '(choice (const :tag "No restrictions" nil)
b9d9c159
JL
2381 (const :tag "When point is on a file name initially, search file names" dwim)
2382 (const :tag "Always search in file names" t))
b4b6bda2
JL
2383 :group 'dired
2384 :version "23.1")
2385
43533626 2386(defvar dired-isearch-filter-predicate-orig nil)
b4b6bda2 2387
f1056735
JL
2388(defun dired-isearch-filenames-toggle ()
2389 "Toggle file names searching on or off.
43533626
JL
2390When on, Isearch skips matches outside file names using the predicate
2391`dired-isearch-filter-filenames' that matches only at file names.
04f0aeaf 2392When off, it uses the original predicate."
f1056735 2393 (interactive)
43533626
JL
2394 (setq isearch-filter-predicate
2395 (if (eq isearch-filter-predicate 'dired-isearch-filter-filenames)
04f0aeaf 2396 dired-isearch-filter-predicate-orig
43533626 2397 'dired-isearch-filter-filenames))
f1056735
JL
2398 (setq isearch-success t isearch-adjusted t)
2399 (isearch-update))
2400
27f7e9b5 2401;;;###autoload
b4b6bda2
JL
2402(defun dired-isearch-filenames-setup ()
2403 "Set up isearch to search in Dired file names.
2404Intended to be added to `isearch-mode-hook'."
b9d9c159
JL
2405 (when (or (eq dired-isearch-filenames t)
2406 (and (eq dired-isearch-filenames 'dwim)
2407 (get-text-property (point) 'dired-filename)))
2408 (setq isearch-message-prefix-add "filename ")
f1056735 2409 (define-key isearch-mode-map "\M-sf" 'dired-isearch-filenames-toggle)
43533626
JL
2410 (setq dired-isearch-filter-predicate-orig
2411 (default-value 'isearch-filter-predicate))
2412 (setq-default isearch-filter-predicate 'dired-isearch-filter-filenames)
b4b6bda2
JL
2413 (add-hook 'isearch-mode-end-hook 'dired-isearch-filenames-end nil t)))
2414
2415(defun dired-isearch-filenames-end ()
2416 "Clean up the Dired file name search after terminating isearch."
b9d9c159 2417 (setq isearch-message-prefix-add nil)
f1056735 2418 (define-key isearch-mode-map "\M-sf" nil)
43533626 2419 (setq-default isearch-filter-predicate dired-isearch-filter-predicate-orig)
b4b6bda2
JL
2420 (remove-hook 'isearch-mode-end-hook 'dired-isearch-filenames-end t))
2421
43533626 2422(defun dired-isearch-filter-filenames (beg end)
04f0aeaf
JL
2423 "Test whether the current search hit is a visible file name.
2424Return non-nil if the text from BEG to END is part of a file
2425name (has the text property `dired-filename') and is visible."
2426 (and (isearch-filter-visible beg end)
b4b6bda2
JL
2427 (if dired-isearch-filenames
2428 (text-property-not-all (min beg end) (max beg end)
2429 'dired-filename nil)
2430 t)))
2431
2432;;;###autoload
2433(defun dired-isearch-filenames ()
2434 "Search for a string using Isearch only in file names in the Dired buffer."
2435 (interactive)
b9d9c159 2436 (let ((dired-isearch-filenames t))
b4b6bda2
JL
2437 (isearch-forward)))
2438
2439;;;###autoload
2440(defun dired-isearch-filenames-regexp ()
2441 "Search for a regexp using Isearch only in file names in the Dired buffer."
2442 (interactive)
b9d9c159 2443 (let ((dired-isearch-filenames t))
b4b6bda2
JL
2444 (isearch-forward-regexp)))
2445
2446\f
2297e912
RM
2447;; Functions for searching in tags style among marked files.
2448
160c8be6
JL
2449;;;###autoload
2450(defun dired-do-isearch ()
2451 "Search for a string through all marked files using Isearch."
2452 (interactive)
2453 (multi-isearch-files
2454 (dired-get-marked-files nil nil 'dired-nondirectory-p)))
2455
2456;;;###autoload
2457(defun dired-do-isearch-regexp ()
2458 "Search for a regexp through all marked files using Isearch."
2459 (interactive)
2460 (multi-isearch-files-regexp
2461 (dired-get-marked-files nil nil 'dired-nondirectory-p)))
2462
2297e912 2463;;;###autoload
5c0b696b 2464(defun dired-do-search (regexp)
2297e912
RM
2465 "Search through all marked files for a match for REGEXP.
2466Stops when a match is found.
2467To continue searching for next match, use command \\[tags-loop-continue]."
2468 (interactive "sSearch marked files (regexp): ")
5e514c27 2469 (tags-search regexp '(dired-get-marked-files nil nil 'dired-nondirectory-p)))
2297e912
RM
2470
2471;;;###autoload
be3981a8 2472(defun dired-do-query-replace-regexp (from to &optional delimited)
5c0b696b 2473 "Do `query-replace-regexp' of FROM with TO, on all marked files.
2297e912 2474Third arg DELIMITED (prefix arg) means replace only word-delimited matches.
e5374284 2475If you exit (\\[keyboard-quit], RET or q), you can resume the query replace
2297e912
RM
2476with the command \\[tags-loop-continue]."
2477 (interactive
0751a704
JL
2478 (let ((common
2479 (query-replace-read-args
2480 "Query replace regexp in marked files" t t)))
2481 (list (nth 0 common) (nth 1 common) (nth 2 common))))
d1c553c8
RS
2482 (dolist (file (dired-get-marked-files nil nil 'dired-nondirectory-p))
2483 (let ((buffer (get-file-buffer file)))
2484 (if (and buffer (with-current-buffer buffer
2485 buffer-read-only))
60a8f928 2486 (error "File `%s' is visited read-only" file))))
5e514c27
RS
2487 (tags-query-replace from to delimited
2488 '(dired-get-marked-files nil nil 'dired-nondirectory-p)))
2489
2490(defun dired-nondirectory-p (file)
2491 (not (file-directory-p file)))
83fadedf 2492\f
ee6be958
MB
2493;;;###autoload
2494(defun dired-show-file-type (file &optional deref-symlinks)
2495 "Print the type of FILE, according to the `file' command.
26bde865
LMI
2496If you give a prefix to this command, and FILE is a symbolic
2497link, then the type of the file linked to by FILE is printed
2498instead."
ee6be958 2499 (interactive (list (dired-get-filename t) current-prefix-arg))
b967bd19
MA
2500 (let (process-file-side-effects)
2501 (with-temp-buffer
2502 (if deref-symlinks
2503 (process-file "file" nil t t "-L" "--" file)
2504 (process-file "file" nil t t "--" file))
2505 (when (bolp)
2506 (backward-delete-char 1))
2507 (message "%s" (buffer-string)))))
2297e912 2508
80ec9ac5
RS
2509(provide 'dired-aux)
2510
276f1d00
GM
2511;; Local Variables:
2512;; byte-compile-dynamic: t
2513;; generated-autoload-file: "dired.el"
2514;; End:
2515
e5167999 2516;;; dired-aux.el ends here